[英]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.