Search code examples
ioscocoa-touchavplayeravplayerlayer

AVPlayerLayer Stopped by Music


I am using an AVPlayerLayer to play a video. The video has no sound. However, if a user is playing music in the background and the AVPlayerLayer is displayed, the music stops. If the user swipes up and hits play, the video stops.

I have even set the muted property of AVPlayer to true yet this still occurs.

How can I prevent the AVPlayerLayer from interfering with any music the user might be playing?


Solution

  • Video decoding seems to interrupt audio apps and vice versa (I think it can even interrupt yourself). You can disable this behaviour by configuring "mix with others" on your audio session:

    NSError *error;
    
    if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error]) {
        // handle error
    }
    
    if (![[AVAudioSession sharedInstance] setActive:YES error:&error]) {
        // handle error
    }
    

    I don't know why, but setting a simple AVAudioSessionCategoryAmbient category with no options works too:

    if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error]) {
        // handle error
    }
    

    I used to have complicated theories on why mix-with-others was necessary and even obvious for this sort of use case, but I've forgotten them and would prefer a pointer to some documentation instead.

    p.s. I'm pretty sure both the above solutions will disable remote control events for your app. hope that's ok. once again, would love some doco.