How to resume AVAudioPlayer after interrupted in background

折月煮酒 提交于 2019-12-04 05:06:18

Found the solution! I had the same problem, my app was resuming the audio nicely after an interruption, only if my app was open. When it was on the background it failed ro resume playing the audio after an interruption.

I fixed this by adding the following lines of code:

Add this line whenever your app start playing audio.[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

And on the endInterruption method, wait 1 or 2 seconds before resume playing the audio. This to allow the OS to stop using the audio channel.

- (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.
                });
        }
    }
}

You can also add this line when your app stops (not pause) playing audio. But is not required. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

Try this

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

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

Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!