AVAudioPlayer 从后台恢复但暂停其他应用程序
AVAudioPlayer resume from background but pause for other apps
我的音频开始和停止都符合我的预期。当我在应用程序后台运行时,音乐会继续播放,如果我激活 Siri,音乐会中断,但随后会按我的预期继续播放。
我遇到的问题是,如果我的声音在后台播放,并且我启动了 Apple Music 或 Podcast,音频会混合在一起,这是我不想要的,但是如果我使用 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()
解决了这个问题,但我不确定为什么。
我的音频开始和停止都符合我的预期。当我在应用程序后台运行时,音乐会继续播放,如果我激活 Siri,音乐会中断,但随后会按我的预期继续播放。
我遇到的问题是,如果我的声音在后台播放,并且我启动了 Apple Music 或 Podcast,音频会混合在一起,这是我不想要的,但是如果我使用 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()
解决了这个问题,但我不确定为什么。