繁体   English   中英

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

[英]Stop AVAudioPlayer music when the app goes to background

我正在开发一个小游戏,并且正在使用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配置为使用类别AVAudioSessionCategorySoloAmbient。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM