Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAudioSession can't play sound after app re-becomes active

So I have a music app that uses an AVAudioSession to allow it to play when it is in the background. I use this call:

[audioSession setActive:YES
            withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation
                  error:nil];

My problem now is if I go to another app and it steals the audio session (thus now stopping music playback from my app and playing something else), and I come back to my app, no matter what I do to reset my audio session or my audio units, my app's sound is gone.

Does anyone know what to do?

like image 859
JackyJohnson Avatar asked Oct 27 '25 05:10

JackyJohnson


1 Answers

So after registering for the AVAudioSession notifications:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(handleAudioSessionInterruption:)
                                             name:AVAudioSessionInterruptionNotification
                                           object:aSession]; 

You need to resume/restart you need to restart your player in the handler interruption type is AVAudioSessionInterruptionTypeEnded:

- (void)handleAudioSessionInterruption:(NSNotification*)notification {

    NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];
    NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey];

    switch (interruptionType.unsignedIntegerValue) {
        case AVAudioSessionInterruptionTypeBegan:{
            // • Audio has stopped, already inactive
            // • Change state of UI, etc., to reflect non-playing state
        } break;
        case AVAudioSessionInterruptionTypeEnded:{
            // • Make session active
            // • Update user interface
            // • AVAudioSessionInterruptionOptionShouldResume option
            if (interruptionOption.unsignedIntegerValue == AVAudioSessionInterruptionOptionShouldResume) {
                // Here you should continue playback.
                [player play];
            }
        } break;
        default:
            break;
    }
}

You can see a complete explanation here: AVplayer resuming after incoming call

like image 55
marosoaie Avatar answered Oct 28 '25 18:10

marosoaie