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

标签 ios swift avplayer

我的音频如我所料开始和停止。当我在应用程序后台运行时,音乐会继续播放,如果我激活 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() 解决了这个问题,但我不确定为什么。

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

相关文章:

swift - 在 SwiftUI/AVPlayer 中与 NotificationCenter/Combine 作斗争

ios - 创建 Cydia Logos Tweak,现在需要在安装后重新启动(怎么做)

ios - Xcode 7.2 Assets 目录更改

iOS Reachability SCNetworkReachabilitySetCallback 当从 wifi 切换到 anthor wifi 时不回调

ios - UICollectionView自定义单元格布局

ios - 如何在使用 AVPlayer 播放视频之前检测 AirPlay 是否处于事件状态?

ios - Tableviewcontroller "cellForRowAtIndexPath"- 索引从 4 开始,而不是 0

swift - 如何使用本地数据保存 subview - swift

ios - 如果尺寸大于 800 像素,则设置最大内容宽度

ios - 在 UITableViewCell 中播放视频的最佳方式是什么