Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/109.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 当应用程序转到后台时停止AVAudioPlayer音乐_Ios_Objective C_Xcode_Sprite Kit_Avaudioplayer - Fatal编程技术网

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

Ios 当应用程序转到后台时停止AVAudioPlayer音乐,ios,objective-c,xcode,sprite-kit,avaudioplayer,Ios,Objective C,Xcode,Sprite Kit,Avaudioplayer,我正在开发一个小游戏,我正在使用AVAudioPlayer来播放游戏的背景音乐。问题是,如果用户退出应用程序时没有在应用程序抽屉中关闭它,因此它处于后台,音乐将不会停止。我怎样才能改变这个?谢谢你的帮助 在处理AVAudioPlayer的ViewController中,将此添加到viewDidLoad中 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) n

我正在开发一个小游戏,我正在使用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];

当然,在激活会话之前请先执行此操作。

退出活动与进入后台不同。使用UIApplicationIdentinterBackground而不是UIApplicationWillResignActive,以便在应用程序进入后台时收到通知。删除应用程序中的观察者将终止通知没有意义。应用程序正在终止。这样的清理在那个阶段是毫无意义的。是的,但我喜欢对称性,而且这个小小的练习确保我永远不会忘记删除通知。