应用正在播放音频(处于活动或背景模式)。来电时,系统停止播放音频。通话结束后如何重新通过应用程序继续播放音频?
这是苹果公司的指南:
遵循指南,我得到了以下代码:
private func setupAudioSession() {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
setupAudioNotifications()
} catch {
print(error)
}
}
private func setupAudioNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption), name: .AVAudioSessionInterruption, object: nil)
}
@objc func handleInterruption(notification: Notification) {
guard let userInfo = notification.userInfo,
let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSessionInterruptionType(rawValue: typeValue) else {
return
}
if type == .began { // NOTE: it works
// Interruption began, take appropriate actions
Player.shared.stop()
} else if type == .ended { // NOTE: it doesn't work
if let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt {
let options = AVAudioSessionInterruptionOptions(rawValue: optionsValue)
if options.contains(.shouldResume) {
// Interruption Ended - playback should resume
Player.shared.start()
} else {
// Interruption Ended - playback should NOT resume
}
}
}
}
.began总是会触发并且播放器停止,但是由于某种原因,.end不会触发,并且继续播放音频的命令也不会发出。
测试方式:我从另一台设备打入电话(并且.began事件触发),在发出哔声之后,我结束了从另一台设备的呼叫(在这种情况下没有handleInterruption()调用)