当应用程序进入后台时,停止播放AVAudioPlayer音乐



我正在开发一个小游戏,我正在使用AVAudioPlayer来播放游戏的背景音乐。问题是,如果用户退出应用程序而没有将其关闭在应用程序抽屉中(因此它在后台),音乐将不会停止。我该如何更改?谢谢你的帮助!

在处理AVAudioPlayer的ViewController中,将其添加到viewDidLoad 中

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

然后添加这两种方法:

-(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");
}

这里的快速答案是,您希望将AVAudioSession配置为使用类别AVAudioSsessionCategorySoloAmbient。

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

当然,这是在您激活会话之前。

最新更新