SPB Git

Repository Public

AudioSessionManager.swift 4.9 KB 105 lines swift

1// SP Music iOS2// File: Core/Sources/SPMusicCore/Audio/AudioSessionManager.swift3// Description: Audio session: background playback, interruptions, output route.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import AVFoundation9import Foundation10import Observation1112public struct AudioRoute: Sendable, Equatable {13    public enum Kind: String, Sendable { case speaker, headphones, bluetooth, airPlay, carPlay, usb, hdmi, other }14    public var name: String15    public var kind: Kind16    /// What the hardware runs at right now. Bluetooth always re-encodes; this is information, not a promise.17    public var sampleRate: Double18    public static let unknown = AudioRoute(name: "", kind: .other, sampleRate: 0)19    public var symbol: String {20        switch kind {21        case .speaker: "iphone.gen3"22        case .headphones: "headphones"23        case .bluetooth: "airpods.pro"24        case .airPlay: "airplayaudio"25        case .carPlay: "car.fill"26        case .usb: "cable.connector"27        case .hdmi: "tv"28        case .other: "hifispeaker"29        }30    }31}3233/// The app's audio session: long-form playback that continues in the background and when the screen is locked,34/// yields to phone calls and other apps, and follows the output the listener picks (AirPods, AirPlay, car).35@MainActor @Observable36public final class AudioSessionManager {37    public private(set) var route = AudioRoute.unknown3839    @ObservationIgnored public var onInterruptionBegan: (@MainActor () -> Void)?40    @ObservationIgnored public var onInterruptionEnded: (@MainActor (_ shouldResume: Bool) -> Void)?41    /// Headphones unplugged, AirPods removed, Bluetooth out of range: playback must not continue on the speaker.42    @ObservationIgnored public var onOutputLost: (@MainActor () -> Void)?43    @ObservationIgnored public var onMediaServicesReset: (@MainActor () -> Void)?44    @ObservationIgnored private var observers: [any NSObjectProtocol] = []45    @ObservationIgnored private var active = false4647    public init() {}4849    #if os(iOS)50    public func configure() {51        let s = AVAudioSession.sharedInstance()52        do { try s.setCategory(.playback, mode: .default, policy: .longFormAudio) }53        catch { Log.audio.error("audio session category: \(error.localizedDescription, privacy: .public)") }54        let nc = NotificationCenter.default55        observers.append(nc.addObserver(forName: AVAudioSession.interruptionNotification, object: s, queue: .main) { [weak self] n in56            let type = (n.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt).flatMap(AVAudioSession.InterruptionType.init)57            let options = AVAudioSession.InterruptionOptions(rawValue: n.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt ?? 0)58            MainActor.assumeIsolated {59                if type == .began { self?.active = false; self?.onInterruptionBegan?() }60                else if type == .ended { self?.onInterruptionEnded?(options.contains(.shouldResume)) }61            }62        })63        observers.append(nc.addObserver(forName: AVAudioSession.routeChangeNotification, object: s, queue: .main) { [weak self] n in64            let reason = (n.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt).flatMap(AVAudioSession.RouteChangeReason.init)65            MainActor.assumeIsolated {66                self?.refreshRoute()67                if reason == .oldDeviceUnavailable { self?.onOutputLost?() }68            }69        })70        observers.append(nc.addObserver(forName: AVAudioSession.mediaServicesWereResetNotification, object: s, queue: .main) { [weak self] _ in71            MainActor.assumeIsolated { self?.active = false; self?.onMediaServicesReset?() }72        })73        refreshRoute()74    }7576    /// Called right before playback starts. Returns false when the system refuses (a phone call is in progress).77    @discardableResult78    public func activate() -> Bool {79        if active { return true }80        do { try AVAudioSession.sharedInstance().setActive(true); active = true; refreshRoute(); return true }81        catch { Log.audio.error("audio session activation: \(error.localizedDescription, privacy: .public)"); return false }82    }8384    public func refreshRoute() {85        let s = AVAudioSession.sharedInstance()86        guard let out = s.currentRoute.outputs.first else { route = .unknown; return }87        let kind: AudioRoute.Kind = switch out.portType {88        case .builtInSpeaker, .builtInReceiver: .speaker89        case .headphones, .headsetMic: .headphones90        case .bluetoothA2DP, .bluetoothLE, .bluetoothHFP: .bluetooth91        case .airPlay: .airPlay92        case .carAudio: .carPlay93        case .usbAudio: .usb94        case .HDMI: .hdmi95        default: .other96        }97        route = AudioRoute(name: out.portName, kind: kind, sampleRate: s.sampleRate)98    }99    #else100    public func configure() {}101    @discardableResult public func activate() -> Bool { true }102    public func refreshRoute() {}103    #endif104}105
Files main
Menu

Theme