// 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 AVFoundationimportFoundationpublicenumVoiceAudioSession {/// Posted on the main thread before the microphone opens. A player that/// is playing pauses and remembers it did.publicstaticlet 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.publicstaticlet didListen = Notification.Name("cotton.voice.didListen")/// Open the session for listening. @MainActorpublicstaticfuncopen() 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) } catchlet error as NSError where error.code == AVAudioSession.ErrorCode.insufficientPriority.rawValue {// A call (or Siri) holds the microphone.throwVoiceFailure.onCall } #endif }/// Release the session: others come back up, Cotton's players resume. @MainActorpublicstaticfunc close() { #if os(iOS)try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) #endifNotificationCenter.default.post(name: didListen, object: nil) }}