Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background audio doesn't resume after a call

My background audio works fine almost all the time. Screen locked, or mute switch on. But when the user has the application in the background, and it receives a call, even if the user doesn't answer the call, the background audio does not resumes after the interruption ends.

The Music app properly resumes background audio if it was interrupted.

Am I missing some property or do I need to have a callback or set a background task to continue background audio execution after an interruption? Or this is something that we can't do?

like image 748
carlos Avatar asked Feb 28 '12 05:02

carlos


2 Answers

We are resuming our audio after an outbound call and inbound call while the app is in the background.

We play audio with AVAudioPlayer and listen to the AVAudioSessionInterruptionNotification. Apple automatically pauses the AVAudioPlayer for you on an interruption and when you tell it to resume after you receive the interruption is over, Apple will set your session active again. See Table 3-2 from Handling Audio Interruptions on recommendations if you are using other types of audio technologies.

Subscribe to the notification:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAudioSessionEvent:) name:AVAudioSessionInterruptionNotification object:nil];

Handle the notification:

- (void) onAudioSessionEvent: (NSNotification *) notification
{
    //Check the type of notification, especially if you are sending multiple AVAudioSession events here
    if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) {
        NSLog(@"Interruption notification received!");

        //Check to see if it was a Begin interruption
        if ([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeBegan]]) {
            NSLog(@"Interruption began!");

        } else {
            NSLog(@"Interruption ended!");
            //Resume your audio
        }
    }
}
like image 131
Michael M. Myers Avatar answered Sep 24 '22 19:09

Michael M. Myers


In my experience I found I had to "wait a second or two" before attempting to reopen the audio device. I think that after the OS switches back to your app from the call, the phone app is still shutting down.

something like this when you return to foreground after knowing your audio session has been stopped:

            dispatch_time_t restartTime = dispatch_time(DISPATCH_TIME_NOW, 
                                                      1.5LL * NSEC_PER_SEC);

            dispatch_after(restartTime, dispatch_get_global_queue(0, 0), ^{ 
                [audioSystem restart]; 
            });
like image 44
Tony Million Avatar answered Sep 22 '22 19:09

Tony Million