我有一个锻炼应用程序,每隔几秒播放一次声音短片。我启用了背景音乐,以便在锻炼时可以播放来自其他应用的音乐。当我得到一个有声音的远程推送通知(在我的情况下,Slack)时会出现问题,这会以某种方式取消我的其他音频会话,而其他应用程序的音乐会再次响亮。
问题 - 当用户遇到这种类型的中断时,如何重置我的duckingOthers音频会话?
我通过调用 didFinishLaunchingWithOptions 中的以下函数来设置音频会话:
private func setupAudioSession(){
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [.mixWithOthers, .duckOthers, .interruptSpokenAudioAndMixWithOthers])
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
我曾尝试将其视为硬中断(例如电话),但在尝试应用此类中断所使用的技术时,似乎远程推送通知会通过裂缝。以下是我从一个不同的问题中尝试捕捉中断的内容。
@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 {
// Interruption began, take appropriate actions
print("interruption started")
}
else if type == .ended {
if let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt {
let options = AVAudioSessionInterruptionOptions(rawValue: optionsValue)
if options.contains(.shouldResume) {
// Interruption Ended - playback should resume
print("should resume playback")
setupAudioSession()
} else {
// Interruption Ended - playback should NOT resume
print("should not resume playback")
}
}
}
}
func setupNotifications() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector: #selector(handleInterruption),
name: .AVAudioSessionInterruption,
object: nil)
}