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

时间:2018-01-19 21:31:34

标签: ios swift avplayer

我的音频按照我的预期开始和停止。当我对应用程序进行后台处理时,音乐会继续播放,如果我激活Siri,音乐会中断,但会按照我的预期重新开始。

我遇到的问题是,如果我的声音在后台播放,我启动Apple Music或播客,音频混合在一起,我不想要,但如果我使用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()
            }
        }
    }

理想情况下,我希望我的应用程序在任何中断后恢复,但如果有任何中断,我也希望我的应用程序停止播放。

由于

1 个答案:

答案 0 :(得分:0)

在设置类别后添加UIApplication.shared.beginReceivingRemoteControlEvents()修复此问题,但我不确定原因。