OGeek|极客世界-中国程序员成长平台

标题: ios - AVAudioPlayer 从后台恢复但暂停其他应用程序 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:37
标题: ios - AVAudioPlayer 从后台恢复但暂停其他应用程序

我的音频按预期开始和停止。当我在后台运行应用程序时,音乐会继续播放,如果我激活 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()
            }
        }
    }

理想情况下,我希望我的应用在任何中断后恢复,但我也希望我的应用在出现任何中断时停止播放。

谢谢



Best Answer-推荐答案


在设置类别后添加 UIApplication.shared.beginReceivingRemoteControlEvents() 解决了这个问题,但我不知道为什么。

关于ios - AVAudioPlayer 从后台恢复但暂停其他应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48349834/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4