如何在后台中断后恢复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];
}
谁能帮我?
找到解决方案! 我遇到了同样的问题,我的应用在中断后很好地恢复了音频,只有当我的应用打开时。 当它在背景上时,失败后恢复播放音频。
我通过添加以下几行代码来解决这个问题:
  只要您的应用程序开始播放音频,就添加此行 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 
并且在endInterruption方法中,等待1或2秒后再继续播放音频。 这样可以让操作系统停止使用音频通道。
- (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.
                });
        }
    }
}
  您也可以在应用程序停止播放音频(而不是暂停)时添加此行。  但不是必需的。 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 
尝试这个
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)audioPlayer withFlags:(NSUInteger)flags{
    if (flags == AVAudioSessionFlags_ResumePlay) {
        [audioPlayer play];
    }    
希望能帮助到你。
链接地址: http://www.djcxy.com/p/57447.html上一篇: How to resume AVAudioPlayer after interrupted in background
下一篇: How to start playing music when app is already in background?
