当应用程序转到后台时停止AVAudioPlayer音乐

时间:2014-09-22 18:08:02

标签: ios objective-c xcode sprite-kit avaudioplayer

我正在开发一款小游戏,并且我正在使用AVAudioPlayer来播放游戏的背景音乐。问题是,如果用户退出应用程序而未在应用程序抽屉中关闭它(因此它在后台),音乐将不会停止。我怎么能改变这个?谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

在处理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");
}

答案 1 :(得分:0)

这里的快速回答是您要将AVAudioSession配置为使用类别AVAudioSessionCategorySoloAmbient。

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

这在您激活课程之前。