I have 2 apps for audio playback, I need to check a case when the first app was interrupted the sound should stops to play, however, when the interruption is end the app should return to playback.
There is a great example with exact implementation of it - https://stackoverflow.com/a/71678102/5709159
The trick is when the interruption app finished its playback this event has to be fired:
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
and the first app (one should continue to play) has to catch this event like this
self.observer = NotificationCenter.default.addObserver(forName:
AVAudioSession.interruptionNotification, object: nil, queue: nil) {
[weak self] n in
guard let self = self else { return } // legal in Swift 4.2
let why = n.userInfo![AVAudioSessionInterruptionTypeKey] as! UInt
let type = AVAudioSession.InterruptionType(rawValue: why)!
switch type {
case .began:
print("interruption began:\n\(n.userInfo!)")
case .ended:
print("interruption ended:\n\(n.userInfo!)")
guard let opt = n.userInfo![AVAudioSessionInterruptionOptionKey] as? UInt else {return}
let opts = AVAudioSession.InterruptionOptions(rawValue: opt)
if opts.contains(.shouldResume) {
print("should resume")
print("Is playing: \(self.player.isPlaying)")
print("is I prepared to play: \(self.player.prepareToPlay())")
print("bp tried to resume play: did I? \(self.player.play())")
} else {
print("not should resume")
}
@unknown default: fatalError()
}
}
The problem is that this line - self.player.prepareToPlay()
returns false
What am I missing here?