[英]AVAudioPlayer resume from background but pause for other apps
我的音頻開始和停止,正如我所期望的。 當我為應用程序提供背景音樂時,音樂會繼續播放,如果我激活Siri,則音樂會中斷,但隨后會恢復到我期望的狀態。
我的問題是,如果我的聲音在后台播放,並且我啟動了Apple Music或Podcasts,則音頻混合在一起,這是我不希望的,但是如果我使用Siri,我的音頻會停止,然后再恢復。
我希望我的音樂停止播放,而我希望其他人像Siri一樣控制音頻。 我曾嘗試刪除.mixWithOthers
但是當我這樣做時,似乎一旦我使我的應用程序后台運行並啟動Siri,此后,即使調用了.ended
情況下的代碼,我的音頻也將無法再次啟動。
func commonInit() {
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption), name: .AVAudioSessionInterruption, object: nil)
}
var shouldResume: Bool = false
@objc func handleInterruption(_ notification: Notification) {
guard let info = notification.userInfo,
let typeValue = info[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSessionInterruptionType(rawValue: typeValue)
else { return }
switch type {
case .began:
player?.pause()
case .ended:
guard let optionsValue = info[AVAudioSessionInterruptionOptionKey] as? UInt
else { return }
let options = AVAudioSessionInterruptionOptions(rawValue: optionsValue)
if options.contains(.shouldResume) {
player?.play()
}
}
}
理想情況下,我希望我的應用在出現任何中斷后能夠恢復播放,但是如果出現任何中斷,我也希望我的應用停止播放。
謝謝
設置類別后添加UIApplication.shared.beginReceivingRemoteControlEvents()
此問題,但我不確定為什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.