2012-04-01 68 views
0

可能重複:
iOS SDK : playing music on the background and switching viewsiOS版SDK:AVAudioPlayer播放音樂的背景和切換視圖不斷重疊

我想在我的應用程序來播放音樂。音樂工作正常,但切換viewControllers並返回到主菜單後,音樂再次播放!這意味着幾個相同的聲音一起玩!我該如何解決這個問題?

firtview.h

#import <UIKit/UIKit.h> 
#import <AVFoundation/AVFoundation.h> 
@interface ViewController : UIViewController{ 

AVAudioPlayer *theAudio; 
} 
@end 

firstview.m

- (void)viewDidLoad 
{ 
NSString *path = [[NSBundle mainBundle] pathForResource:@"GENIEAPP" ofType:@"mp3"]; 
theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 

theAudio.numberOfLoops = -1; 




[super viewDidLoad]; 

回答

1

你可能有一些問題在這裏,首先當你在玩的觀點負載的聲音,現在我不知道,如果你試圖解除分配視圖viewController,但是當你這樣做時,你可能不會釋放和停止聲音,所以你漏了AVAudioPlayer,因爲你不釋放並停止播放音頻播放器,當你回到播放器時重新分配播放器視圖控制器,它會重新開始播放......不確定你的意圖是什麼,但是如果他們只是在視圖控制器被分配時播放聲音,那麼你應該在dealloc方法或任何地方appripriate,停止avaudioplayer和釋放它...如果你試圖通過播放你的聲音該應用程序,那麼你需要在其他地方也許分配玩家... 看你的評論,這樣的財產以後可能會做的伎倆爲您

-(void)viewDidLoad 
{ 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"GENIEAPP" ofType:@"mp3"]; 
    if(!theAudio){ 
     theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 

     theAudio.numberOfLoops = -1; 
     [theAudio play]; 
    } 
    else 
    { 
     //stop the sound and play it again 
     [theAudio stop]; 
     [theAudio play]; 
    } 
} 
+0

嗯,我想的聲音時,我要在我的3次和播放點擊主頁按鈕返回到我的第一個視圖,我希望音樂重新開始。有沒有更好的方法來完成我想要做的事情?如果這是我應該做的,我該從哪裏開始? – 2012-04-02 05:41:26

+0

當viewDidLoad第二次觸發時,您的音頻播放器已經分配了嗎? – Daniel 2012-04-02 15:04:56

+0

嗯,當ViewDidLoad第一次開始分配 – 2012-04-03 03:00:42