Picture in Picture stops audio when phone locked

AVPlayerViewController has the functionality to keep playing the audio when the app is backgrounded or the device is locked.

Obviously picture in picture improves this when the app is backgrounded but we lose the functionality when the device is locked as it stops the audio. The user can hit play on the lock-screen to continue playing but doesn't seem to be ideal.

Is there any way around this or is the expected behaviour?

Replies

Same question...have you found a solution?

You would need something like these functions when the app is backgrounded and then foregrounded:

    func enterIntoBackground() {
        if #available(iOS 14, *) {
            if self.player?.rate == 1 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in
                    if self?.player?.rate == 0 {
                        self?.playerViewController?.player = nil
                        self?.player?.play()
                    }
                }
            }
        } else {
            self.playerViewController?.player = nil
        }
    }

    func enterIntoForeground() {
        if #available(iOS 14, *) {
            // When the phone was locked in full screen mode
            guard let vc = self.playerViewController else { return }
            if vc.player == nil {
                vc.player = self.player
            }
        } else {
            self.playerViewController?.player = self.player
        }
    }

Hi there,

If you're using iOS 15+, you can use this solution:

if #available(iOS 15.0, *) {
   player?.audiovisualBackgroundPlaybackPolicy = .continuesIfPossible
 } else {
   // Have no idea how to handle it
 }