繁体   English   中英

如何在后台中断后恢复AVAudioPlayer

[英]How to resume AVAudioPlayer after interrupted in background

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

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM