Repository Public License
1//2// ORIX Audio3// File: ORIXAudio/Services/AudioSessionManager.swift4// Description: AVAudioSession configuration, input selection and route description for recording and playback.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import AVFoundation10import Foundation1112struct AudioInputDescription: Identifiable, Hashable, Sendable {13 var id: String // port UID14 var name: String15 var typeLabel: String16 var isBuiltIn: Bool17}1819/// What the hardware is actually delivering right now. Shown verbatim in the UI — nothing is assumed.20struct ActiveRoute: Equatable, Sendable {21 var inputName: String22 var sampleRate: Double23 var inputChannels: Int24 var outputName: String25 var isBluetoothInput: Bool26}2728enum AudioSessionError: Error, LocalizedError {29 case microphoneDenied, noInput, activationFailed(String)30 var errorDescription: String? {31 switch self {32 case .microphoneDenied: String(localized: "Microphone access is off for ORIX Audio. You can turn it on in Settings.")33 case .noInput: String(localized: "No audio input is available.")34 case .activationFailed(let m): String(localized: "The audio system couldn't start (\(m)). Another app may be using the microphone.")35 }36 }37}3839@MainActor40final class AudioSessionManager {41 static let shared = AudioSessionManager()42 private let session = AVAudioSession.sharedInstance()4344 var microphonePermission: AVAudioApplication.recordPermission { AVAudioApplication.shared.recordPermission }4546 func requestMicrophoneAccess() async -> Bool { await AVAudioApplication.requestRecordPermission() }4748 /// Configures and activates the session for capture.49 /// - Parameters:50 /// - stereo: asks the built-in microphones for a stereo pattern when they offer one.51 /// - allowBluetoothMicrophone: Bluetooth hands-free microphones are narrow-band; off by default.52 /// - rawInput: `.measurement` mode (no automatic gain or voice processing by the system).53 func activateForRecording(stereo: Bool, allowBluetoothMicrophone: Bool, rawInput: Bool, preferredInputID: String?) throws {54 var options: AVAudioSession.CategoryOptions = [.defaultToSpeaker, .allowBluetoothA2DP]55 if allowBluetoothMicrophone { options.insert(.allowBluetoothHFP) }56 do {57 try session.setCategory(.playAndRecord, mode: rawInput ? .measurement : .default, options: options)58 if let preferredInputID, let port = session.availableInputs?.first(where: { $0.uid == preferredInputID }) { try? session.setPreferredInput(port) }59 try session.setActive(true)60 } catch { throw AudioSessionError.activationFailed(error.localizedDescription) }61 guard let input = session.currentRoute.inputs.first ?? session.availableInputs?.first else { throw AudioSessionError.noInput }62 configureStereo(stereo, on: input)63 }6465 /// Stereo capture from the built-in microphones is only possible when a data source advertises the stereo polar pattern.66 private func configureStereo(_ wanted: Bool, on input: AVAudioSessionPortDescription) {67 guard input.portType == .builtInMic, let sources = input.dataSources else { return }68 if wanted, let source = sources.first(where: { $0.supportedPolarPatterns?.contains(.stereo) == true }) {69 try? source.setPreferredPolarPattern(.stereo)70 try? input.setPreferredDataSource(source)71 try? session.setPreferredInputOrientation(.portrait)72 } else if let source = input.selectedDataSource ?? sources.first, source.selectedPolarPattern == .stereo {73 try? source.setPreferredPolarPattern(source.supportedPolarPatterns?.first { $0 != .stereo } ?? .omnidirectional)74 }75 }7677 func activateForPlayback() {78 try? session.setCategory(.playback, mode: .default, options: [])79 try? session.setActive(true)80 }8182 func deactivate() { try? session.setActive(false, options: .notifyOthersOnDeactivation) }8384 var availableInputs: [AudioInputDescription] {85 // availableInputs is only populated for a record-capable category.86 if session.category != .playAndRecord && session.category != .record { try? session.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetoothA2DP, .allowBluetoothHFP]) }87 return (session.availableInputs ?? []).map {88 AudioInputDescription(id: $0.uid, name: $0.portName, typeLabel: Self.label($0.portType), isBuiltIn: $0.portType == .builtInMic)89 }90 }9192 var activeRoute: ActiveRoute {93 let route = session.currentRoute94 let input = route.inputs.first95 return ActiveRoute(inputName: input?.portName ?? String(localized: "No input"), sampleRate: session.sampleRate, inputChannels: session.inputNumberOfChannels,96 outputName: route.outputs.first?.portName ?? "—", isBluetoothInput: input.map { $0.portType == .bluetoothHFP || $0.portType == .bluetoothLE } ?? false)97 }9899 static func label(_ type: AVAudioSession.Port) -> String {100 switch type {101 case .builtInMic: String(localized: "Built-in microphone")102 case .headsetMic: String(localized: "Wired headset")103 case .bluetoothHFP, .bluetoothLE: String(localized: "Bluetooth")104 case .usbAudio: String(localized: "USB audio")105 case .lineIn: String(localized: "Line in")106 default: String(localized: "External")107 }108 }109}110