2
votes

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.

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.

I want my music to stop and the other to take control of the audio just like it does with 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.

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

1
Without the mixWithOthers option, your session may have ended. Try adding try AVAudioSession.sharedInstance().setActive(true) in the case .ended block.picciano
Unfortunately that too does not work :( try? AVAudioSession.sharedInstance().setActive(true) returns nilJack Wilkinson

1 Answers

0
votes

Adding UIApplication.shared.beginReceivingRemoteControlEvents() after setting the category fixed this issue but I'm not sure why.