当应用程序转到背景时停止AVAudioPlayer音乐

问题描述:

我正在开发一个小游戏,我正在使用AVAudioPlayer来播放游戏的背景音乐。问题是,如果用户在应用程序抽屉中关闭应用程序而未关闭应用程序(因此它位于后台),则音乐不会停止。我该如何改变这一点?谢谢你的帮助!当应用程序转到背景时停止AVAudioPlayer音乐

在视图控制器,你处理你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

这里简单的回答是,你要配置的AVAudioSession使用类别AVAudioSessionCategorySoloAmbient。

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

这在你激活会话当然。