2011-04-23 71 views
2

如何在更改視圖時停止背景音樂?我沒有任何線索。如果我按下一個按鈕,帶我到一個新的視圖,有新的背景音樂。但是舊的背景音樂(無限循環)一直在繼續。請幫忙!也請示例一些代碼,這裏是我的:iOS - 如何在更改視圖時停止背景音樂

- (void)viewDidLoad { 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"MathMusic2" ofType:@"wav"]; 
    AVAudioPlayer* theAudio= [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    theAudio.delegate = self; 
    [theAudio play]; 
    theAudio.numberOfLoops = -1; 

    [super viewDidLoad]; 
} 

我只需要知道如何使新視圖的背景音樂停止播放。反之亦然,當我按下新視圖中的後退按鈕時

回答

4

AVAudioPlayer *theAudio創建一個屬性,以便您可以從班級中的任何位置訪問audioPlayer。的viewController的

頭文件

... 
AVAudioPlayer *theAudio; 
... 
@property (nonatomic, retain) AVAudioPlayer *theAudio; 

的viewController的Implentation文件

... 
@synthesize theAudio; 
... 

- (void)viewDidLoad { 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"MathMusic2" ofType:@"wav"]; 
    self.theAudio= [[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]] autorelease]; 
    theAudio.delegate = self; 
    [theAudio play]; 
    theAudio.numberOfLoops = -1; 

    [super viewDidLoad]; 
} 

如果viewWillDisappear被稱爲那麼你可以停止音頻與

- (void)viewWillDisappear 
{ 
    [theAudio stop]; 
} 
+0

太多errorrs – user722566 2011-04-23 15:14:24

+3

@ user721820赦免? – 2011-04-23 15:15:11

-1

它在這裏給出了錯誤: 「theAudio.delegate = self;」就像這樣分配給ID ...

它的黃色反正.. 仍然當我改變看法,並轉到另一級的音樂不回採....

+1

在viewController.h中添加AVAudioPlayerDelegate – Nishant 2012-12-28 19:14:04