Search code examples
iosaudioavfoundationavplayeravplayerlayer

AVPlayerLayer pauses currently playing audio


I have a ViewController which I add an AVPlayerLayer to have a video background. For that I use AVPlayerLayer and add it to the view's layer. If I have Spotify or anything else playing audio playing while opening that ViewController the PlayerLayer pauses it.

How can I end this behavior?

I create my layer like this:

lazy var playerLayer:AVPlayerLayer! = { 
    var playerLayer:AVPlayerLayer!
    if let src = NSBundle.mainBundle().pathForResource("Untitled", ofType: "mp4") {
        playerLayer = AVPlayerLayer(player: AVPlayer(URL: NSURL.fileURLWithPath(src)))
        playerLayer.frame = self.view.bounds
        playerLayer.backgroundColor = nil
        playerLayer.opaque = true
        playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

        playerLayer.player?.muted = true

        self.view.layer.insertSublayer(playerLayer, atIndex: 0)
    }

    return playerLayer
}()

As you can see Ive tried with setting the muted property to true, but it doesnt work.


Solution

  • The other apps' audio is interrupting yours.

    You need to create an AVAudioSession and set the "mix with others" option.

    try? AVAudioSession.sharedInstance().setActive(true)
    try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: .MixWithOthers)