From 169b9451ed26d977bde6b2ffba83d1467d9bf114 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Toni=20F=C3=B6rster?= Date: Wed, 24 Apr 2024 14:43:51 +0200 Subject: [PATCH] handle audio session interrupts by other media fixes #495 --- Model/Player/Backends/MPVBackend.swift | 40 +++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/Model/Player/Backends/MPVBackend.swift b/Model/Player/Backends/MPVBackend.swift index c8457946..223cdf78 100644 --- a/Model/Player/Backends/MPVBackend.swift +++ b/Model/Player/Backends/MPVBackend.swift @@ -254,7 +254,18 @@ final class MPVBackend: PlayerBackend { let startPlaying = { #if !os(macOS) - try? AVAudioSession.sharedInstance().setActive(true) + do { + try AVAudioSession.sharedInstance().setActive(true) + + NotificationCenter.default.addObserver( + self, + selector: #selector(self.handleAudioSessionInterruption(_:)), + name: AVAudioSession.interruptionNotification, + object: nil + ) + } catch { + self.logger.error("Error setting up audio session: \(error)") + } #endif DispatchQueue.main.async { [weak self] in @@ -627,4 +638,31 @@ final class MPVBackend: PlayerBackend { logger.info("MPV backend received unhandled property: \(name)") } } + + @objc func handleAudioSessionInterruption(_ notification: Notification) { + logger.info("Audio session interruption received.") + + guard let info = notification.userInfo, + let typeValue = info[AVAudioSessionInterruptionTypeKey] as? UInt + else { + logger.info("AVAudioSessionInterruptionTypeKey is missing or not a UInt in userInfo.") + return + } + + let type = AVAudioSession.InterruptionType(rawValue: typeValue) + + logger.info("Interruption type received: \(String(describing: type))") + + switch type { + case .began: + pause() + logger.info("Audio session interrupted.") + default: + break + } + } + + deinit { + NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: nil) + } }