简体   繁体   English

AVAudioPlayer从后台恢复,但暂停其他应用程序

[英]AVAudioPlayer resume from background but pause for other apps

My audio starts and stops as I would expect. 我的音频开始和停止,正如我所期望的。 When I background the app the music keeps playing, if I activate Siri, the music interrupts but then resumes as I would expect. 当我为应用程序提供背景音乐时,音乐会继续播放,如果我激活Siri,则音乐会中断,但随后会恢复到我期望的状态。

The issue I have is that, if my sounds are playing in the background, and I start up Apple Music or Podcasts, the audio mixes together which I don't want however if I use Siri, my audio stops then resumes after. 我的问题是,如果我的声音在后台播放,并且我启动了Apple Music或Podcasts,则音频混合在一起,这是我不希望的,但是如果我使用Siri,我的音频会停止,然后再恢复。

I want my music to stop and the other to take control of the audio just like it does with Siri. 我希望我的音乐停止播放,而我希望其他人像Siri一样控制音频。 I have tried removing .mixWithOthers but when I do that, it seems that once I background my app and I start Siri, afterwards my audio is no longer able to start again even though the code within the .ended case is called. 我曾尝试删除.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()
            }
        }
    }

Ideally I want my app to resume after any interruptions, but I also want my app to stop playing if there are any interruptions. 理想情况下,我希望我的应用在出现任何中断后能够恢复播放,但是如果出现任何中断,我也希望我的应用停止播放。

Thanks 谢谢

设置类别后添加UIApplication.shared.beginReceivingRemoteControlEvents()此问题,但我不确定为什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM