菜鸟教程小白 发表于 2022-12-11 19:37:58

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


                                            <p><p>我的音频按预期开始和停止。当我在后台运行应用程序时,音乐会继续播放,如果我激活 Siri,音乐会中断,但随后会按我的预期继续播放。</p>

<p>我遇到的问题是,如果我的声音在后台播放,并且我启动 Apple Music 或 Podcast,音频会混合在一起,这是我不想要的,但是如果我使用 Siri,我的音频会停止,然后在之后恢复.</p>

<p>我希望我的音乐停止,而另一个人控制音频,就像使用 Siri 一样。我已经尝试删除 <code>.mixWithOthers</code> 但是当我这样做时,似乎一旦我后台我的应用程序并启动 Siri,之后我的音频不再能够重新开始,即使 <code 中的</code>.ended</code> 案例被调用。</p>

<pre><code>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 as? UInt,
            let type = AVAudioSessionInterruptionType(rawValue: typeValue)
      else { return }

      switch type {
      case .began:
            player?.pause()
      case .ended:
            guard let optionsValue = info as? UInt
                else { return }
            let options = AVAudioSessionInterruptionOptions(rawValue: optionsValue)

            if options.contains(.shouldResume) {
                player?.play()
            }
      }
    }
</code></pre>

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

<p>谢谢</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>在设置类别后添加 <code>UIApplication.shared.beginReceivingRemoteControlEvents()</code> 解决了这个问题,但我不知道为什么。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - AVAudioPlayer 从后台恢复但暂停其他应用程序,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/48349834/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/48349834/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - AVAudioPlayer 从后台恢复但暂停其他应用程序