我使用 AVAudioPlayer 来播放音频。我启用了背景音频并且音频会话配置正确。
我实施了audioSessionGotInterrupted
音频会话中断时收到通知的方法。这是我当前的代码:
@objc private func audioSessionGotInterrupted(note: NSNotification) {
guard let userInfo = note.userInfo,
let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSessionInterruptionType(rawValue: typeValue) else {
return
}
if type == .began {
print("interrupted")
// Interruption began, take appropriate actions
player.pause()
saveCurrentPlayerPosition()
}
else if type == .ended {
if let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt {
let options = AVAudioSessionInterruptionOptions(rawValue: optionsValue)
if options == .shouldResume {
print("restored")
// Interruption Ended - playback should resume
setupPlayer()
player.play()
} else {
// Interruption Ended - playback should NOT resume
// just keep the player paused
}
}
}
}
现在我执行以下操作:
- 播放一些音频
- 锁定手机
- 暂停音频
- 等待几秒钟,直到我在 XCode 调试器中看到该应用程序已在后台停止
- 我在锁屏界面点击播放
我的指挥中心play()
方法按预期被调用。然而也audioSessionGotInterrupted
方法被调用type == .began
.
这怎么可能?我预计不会看到此类通知,或者至少不会.ended
我使用的是 iOS 10 beta 8。
检查这个
https://developer.apple.com/documentation/avfoundation/avaudiosession/1616596-interruptionnotification https://developer.apple.com/documentation/avfoundation/avaudiosession/1616596-interruptionnotification
从 iOS 10 开始,系统将停用大多数应用程序的音频会话,以响应应用程序进程被挂起。当应用程序再次开始运行时,它将收到一条中断通知,表明其音频会话已被系统停用。该通知必然会被及时延迟,因为只有在应用程序再次运行时才能传递该通知。如果您的应用程序的音频会话因此而暂停,则 userInfo 字典将包含值为 true 的 AVAudioSessionInterruptionWasSuspishedKey 键。
如果您的音频会话配置为不可混合(播放、playAndRecord、soloAmbient 和 multiRoute 类别的默认行为),并且在进入后台时未主动使用音频,建议您停用音频会话。这样做可以避免您的音频会话被系统停用(并收到这种有些令人困惑的通知)。
if let reason = AVAudioSessionInterruptionType(rawValue: reasonType as! UInt) {
switch reason {
case .began:
var shouldPause = true
if #available(iOS 10.3, *) {
if let _ = notification.userInfo?[AVAudioSessionInterruptionWasSuspendedKey] {
shouldPause = false
}
}
if shouldPause {
self.pause()
}
break
case .ended:
break
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)