2014-09-22 135 views
0

我正在開發一個小遊戲,我正在使用AVAudioPlayer來播放遊戲的背景音樂。問題是,如果用戶在應用程序抽屜中關閉應用程序而未關閉應用程序(因此它位於後臺),則音樂不會停止。我該如何改變這一點?謝謝你的幫助!當應用程序轉到背景時停止AVAudioPlayer音樂

回答

0

在視圖控制器,你處理你AVAudioPlayer在viewDidLoad中添加此

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil]; 

然後添加的2種方法:

-(void) appWillResignActive:(NSNotification*)note{ 
    NSLog(@"App is going to the background"); 
    // This is where you stop the music 
} 
-(void) appWillTerminate:(NSNotification*)note{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil]; 

    NSLog(@"App will terminate"); 
} 
+0

「resign active」與進入後臺不一樣。當應用程序進入後臺時,使用'UIApplicationDidEnterBackground'而不是'UIApplicationWillResignActive'來通知。 – rmaddy 2015-04-17 16:22:22

+0

在「應用程序將終止」通知中刪除觀察者沒有任何意義。該應用正在終止。這種清理在那個階段毫無意義。 – rmaddy 2015-04-17 16:23:38

+0

確實如此,但我喜歡這種對稱性,而這一點練習可確保我永遠不會忘記刪除通知。 – ElectrikSheep 2015-06-18 09:42:44

0

這裏簡單的回答是,你要配置的AVAudioSession使用類別AVAudioSessionCategorySoloAmbient。

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil]; 

這在你激活會話當然。

相關問題