How to resume AVAudioPlayer after interrupted in the background

I play music using AVAudioPlayer in the background. The problem is that if an incoming call interrupts the player, it will never resume unless you switch to the foreground and do it manually.

The code is simple to play it in the background:

[[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]; 

to handle interrupts:

 -(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]; } 

Can anyone help me?

+6
source share
2 answers

Found a solution! I had the same problem, my application resumed sound after interruption only if my application was open. When he was in the background, he was unable to resume the sound after the interruption.

I fixed this by adding the following lines of code:

Add this line when your application starts playing audio. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

And at the end of the Internet method, wait 1 or 2 seconds before resuming audio playback. This will 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 application stops (does not stop) while playing audio. But not required. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

+8
source

try it

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

Hope this helps.

0
source

Source: https://habr.com/ru/post/904727/


All Articles