Cotton code
51 lines · 2.3 KB · SwiftRaw
// The audio session while the microphone is open, and the players around it.//// Dictation and a playing song cannot share the air: the microphone would// write the lyrics down. So when listening starts, Cotton's own players are// asked to PAUSE (a spoken podcast and a song alike: ducked speech is still// speech) and other apps' audio is DUCKED by the session's own option; when// listening ends, the session is let go with `notifyOthersOnDeactivation`, so// other apps come back up, and Cotton's players resume if they were playing.//// The ask is a notification rather than a reference: the players live in// CottonUI and in apps that may not link them; each player observes// ``VoiceAudioSession/willListen`` and ``didListen`` and answers for itself.@preconcurrency import AVFoundationimport Foundationpublic enum VoiceAudioSession {    /// Posted on the main thread before the microphone opens. A player that    /// is playing pauses and remembers it did.    public static let willListen = Notification.Name("cotton.voice.willListen")    /// Posted on the main thread after the microphone has closed and the    /// session is released. A player that paused for listening resumes.    public static let didListen = Notification.Name("cotton.voice.didListen")    /// Open the session for listening.    @MainActor    public static func open() throws {        NotificationCenter.default.post(name: willListen, object: nil)        #if os(iOS)            let session = AVAudioSession.sharedInstance()            try session.setCategory(                .playAndRecord, mode: .measurement,                options: [.duckOthers, .defaultToSpeaker, .allowBluetoothHFP])            do {                try session.setActive(true, options: .notifyOthersOnDeactivation)            } catch let error as NSError where error.code == AVAudioSession.ErrorCode.insufficientPriority.rawValue {                // A call (or Siri) holds the microphone.                throw VoiceFailure.onCall            }        #endif    }    /// Release the session: others come back up, Cotton's players resume.    @MainActor    public static func close() {        #if os(iOS)            try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)        #endif        NotificationCenter.default.post(name: didListen, object: nil)    }}