如何在后台中断后恢复AVAudioPlayer

我在后台使用AVAudioPlayer播放音乐。 问题是:如果有传入的呼叫中断播放器,它将永远不会恢复,除非切换到前景并手动执行。

代码很简单,在后台播放:

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error: nil]; [[AVAudioSession sharedInstance] setActive: YES error: nil]; url = [[NSURL alloc] initFileURLWithPath:...]; audio_player = [[AVAudioPlayer alloc] initWithContentsOfURL: url error:NULL]; audio_player.delegate = self; bool ret = [audio_player play]; 

委托来处理中断:

 -(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player { //tried this, not working [[AVAudioSession sharedInstance] setActive: NO error: nil]; NSLog(@"-- interrupted --"); } //----------- THIS PART NOT WORKING WHEN RUNNING IN BACKGROUND ---------- - (void)audioPlayerEndInterruption:(AVAudioPlayer *)player { NSLog(@"resume!"); //--- tried, not working: [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error: nil]; //--- tried, not working: [[AVAudioSession sharedInstance] setActive: YES error: nil]; //--- tried, not working: [audio_player prepareToPlay]; [audio_player play]; } 

谁能帮我?

find解决scheme! 我遇到了同样的问题,我的应用程序在中断后很好地恢复了audio,只有当我的应用程序打开时。 当它在背景上时,中断后恢复播放audio失败。

我通过添加以下几行代码来解决这个问题:

只要您的应用程序开始播放audio,就添加此行 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

然后在endInterruption方法中,等待1或2秒后再继续播放audio。 这样可以让操作系统停止使用audio通道。

 - (void)endInterruptionWithFlags:(NSUInteger)flags { // Validate if there are flags available. if (flags) { // Validate if the audio session is active and immediately ready to be used. if (AVAudioSessionInterruptionFlags_ShouldResume) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), ^{ // Resume playing the audio. }); } } } 

您也可以在应用程序停止播放audio(而不是暂停)时添加此行。 但不是必需的。 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

尝试这个

 -(void)audioPlayerEndInterruption:(AVAudioPlayer *)audioPlayer withFlags:(NSUInteger)flags{ if (flags == AVAudioSessionFlags_ResumePlay) { [audioPlayer play]; } 

希望能帮助到你。