AVPlayer audioSessionGotInterrupted notification when waking up from background

后端 未结 2 908
Happy的楠姐
Happy的楠姐 2021-02-06 03:11

I use AVAudioPlayer to play audio. I have background audio enabled and the audio sessions are configured correctly.

I implemented the audioSessionGotInterrupted

2条回答
  •  囚心锁ツ
    2021-02-06 03:51

    While the answer above is not wrong it still caused a lot of trouble in my app and a lot of boilerplate code for checking multiple cases.

    If you read the description of AVAudioSessionInterruptionWasSuspendedKey it says that the notification is thrown if you didn't deactivate your audio session before your app was sent to the background (which happens every time you lock the screen)

    To solve this issue you simply have to deactivate your session if there is no sound playing when app is sent to background and activate it back if the sound is playing. After that you will not receive the AVAudioSessionInterruptionWasSuspendedKey notification.

       NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { sender in
            guard self.player.isPlaying == false else { return }
            self.setSession(active: false)
        }
    
        NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { sender in
            guard self.player.isPlaying else { return }
            self.setSession(active: true)
        }
    
    func setSession(active: Bool) -> Bool {
        let session = AVAudioSession.sharedInstance()
        do {
            try session.setCategory(.playback, mode: .default)
            try session.setActive(active)
            return true
        } catch let error {
            print("*** Failed to activate audio session: \(error.localizedDescription)")
            return false
        }
    }
    

    Note: Activating session is probably not necessary because it is handled by Apple's internal playback classes (like AVPlayer for example) but it is a good practice to do it manually.

提交回复
热议问题