【发布时间】:2014-09-22 18:08:01
【问题描述】:
我正在开发一个小游戏,我正在使用 AVAudioPlayer 来播放游戏的背景音乐。问题是,如果用户退出应用程序而不在应用程序抽屉中关闭它(所以它在后台),音乐将不会停止。我怎样才能改变这个?感谢您的帮助!
【问题讨论】:
标签: ios objective-c xcode sprite-kit avaudioplayer
我正在开发一个小游戏,我正在使用 AVAudioPlayer 来播放游戏的背景音乐。问题是,如果用户退出应用程序而不在应用程序抽屉中关闭它(所以它在后台),音乐将不会停止。我怎样才能改变这个?感谢您的帮助!
【问题讨论】:
标签: ios objective-c xcode sprite-kit 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");
}
【讨论】:
UIApplicationDidEnterBackground 而不是UIApplicationWillResignActive 得到通知。
这里的快速回答是您希望将 AVAudioSession 配置为使用类别 AVAudioSessionCategorySoloAmbient。
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil];
这当然是在你激活会话之前。
【讨论】: