feat: Handle resuming iOS audio after pause

This commit is contained in:
ronaldheft 2022-08-30 22:47:55 -04:00
parent 20d932877e
commit 11f22888d5

View file

@ -71,6 +71,7 @@ class AudioPlayer: NSObject {
}
// Listen to player events
self.setupInteruptionNotification()
self.audioPlayer.addObserver(self, forKeyPath: #keyPath(AVPlayer.rate), options: .new, context: &playerContext)
self.audioPlayer.addObserver(self, forKeyPath: #keyPath(AVPlayer.currentItem), options: .new, context: &playerContext)
@ -119,6 +120,7 @@ class AudioPlayer: NSObject {
print(error)
}
self.removeInteruptionNotification()
DispatchQueue.runOnMainQueue {
UIApplication.shared.endReceivingRemoteControlEvents()
}
@ -146,6 +148,14 @@ class AudioPlayer: NSObject {
return 0
}
private func setupInteruptionNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(handleInteruption), name: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance())
}
private func removeInteruptionNotification() {
NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance())
}
private func setupTimeObserver() {
// Time observer should be configured on the main queue
DispatchQueue.runOnMainQueue {
@ -588,6 +598,25 @@ class AudioPlayer: NSObject {
}
}
// MARK: - iOS audio interupt notifications
@objc private func handleInteruption(notification: Notification) {
guard let userInfo = notification.userInfo,
let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSession.InterruptionType(rawValue: typeValue) else {
return
}
switch type {
case .ended:
guard let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt else { return }
let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
if options.contains(.shouldResume) {
self.play(allowSeekBack: true)
}
default: ()
}
}
// MARK: - Now playing
private func setupRemoteTransportControls() {
DispatchQueue.runOnMainQueue {