如何在后台中断后恢复AVAudioPlayer

时间:2011-12-30 05:31:09

标签: iphone ios audio background multitasking

我在后台使用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];
}

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:8)

找到解决方案! 我有同样的问题,我的应用程序在中断后很好地恢复音频,只有我的应用程序打开。当它在背景上时,它会在中断后继续播放音频。

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

每当您的应用开始播放音频时添加此行。[[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];

答案 1 :(得分:0)

试试这个

-(void)audioPlayerEndInterruption:(AVAudioPlayer *)audioPlayer withFlags:(NSUInteger)flags{

    if (flags == AVAudioSessionFlags_ResumePlay) {
        [audioPlayer play];
    }    

希望它有所帮助。