mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-25 01:30:06 +08:00
iOS: dictation picks the car's mic in CarPlay, and a warm session never holds call audio (#2179)
Settings › Dictation › Microphone (Automatic, iPhone, Bluetooth) replaces the Always use iPhone microphone switch. In a car the old default recorded from the iPhone, often in a cupholder hearing the speakers and the road, while the car's microphone sat unused; Hex's own recording mixes, so the car went on playing over it. Automatic (the default) now records from a wired or USB headset's microphone, from the car's in CarPlay (the driver's microphone Siri uses), else from the iPhone's, so AirPods and other Bluetooth headphones keep playing at full quality and nothing waits for call audio. iPhone is the old default; Bluetooth also takes Bluetooth hands-free microphones (AirPods, Bluetooth car kits, which iOS can't tell from headphones). The stored switch migrates: left on reads as Automatic, turned off as Bluetooth. Changed behaviour: - The input is always set explicitly (MicrophoneRoute). Before, Bluetooth mode set no preferred input, so an iPhone preference set earlier in the same session stuck, and Automatic-style CarPlay/wired choices didn't exist. - The warm keepalive stays on the iPhone's microphone without HFP whatever the choice. Before, with the switch off, it took the headset's or car's hands-free microphone for the whole warm session (up to an hour of call audio). A dictation moves to its input as it starts; a new route device re-pins the keepalive in every mode, not only with Bluetooth allowed. - In-keyboard dictation asks WebKit for the same input by its label (getUserMedia deviceId), read from the keyboard's own session. Before, with the switch off it asked for nothing, and WebKit takes the input of the route already playing, the iPhone's while a car or headphones play over A2DP, so the switch had no effect there. The probe log now lists the inputs offered and the one chosen. Kept: mixWithOthers, no preferred sample rate, RetiredRecorders, keepalive backoff, and the keyboard's resume request after WebKit's capture. Verified: xcodebuild test on an iPhone 18 Pro simulator (iOS 27.2) on the Mac Studio, 519 tests, 0 failures (1 opt-in skip), including new cases for each choice on each route (CarPlay, AirPods, Bluetooth car kit, wired headset, nothing), the keepalive's input, HFP only for Bluetooth, the migration and the controller passing its choice to the capture. Settings row rendered in English and Simplified Chinese. The simulator has no Bluetooth or CarPlay: the route behaviour itself is unverified on an iPhone.
This commit is contained in:
@@ -203,28 +203,29 @@ final class KeyboardLocalDictation {
|
||||
/// The keyboard extension itself may not record (audiomxd: "it is an extension and
|
||||
/// doesn't have entitlements to record audio"), so capture runs in WebKit's media
|
||||
/// process through getUserMedia, attributed to Hex's microphone permission.
|
||||
/// With Always use iPhone microphone (the app's default), the page asks for the iPhone's own
|
||||
/// microphone, so a car or headset doesn't switch to call audio, which stalls the start.
|
||||
/// The page asks for Settings › Microphone's input by name (`microphone(for:)`): left to
|
||||
/// itself, WebKit takes the input of the route already playing, the iPhone's microphone
|
||||
/// while a car or headphones play over A2DP, whatever the setting.
|
||||
/// WebKit's capture session doesn't mix: other apps' video and music pause while it
|
||||
/// records, and `releaseAudioSession` asks them to resume afterwards.
|
||||
/// `pressedAt` is the Hex key's touch-down (wall clock), where the start's timeline begins.
|
||||
/// A capture armed at touch-down becomes this dictation.
|
||||
func start(in host: UIView, allowBluetoothMic: Bool, pressedAt: TimeInterval? = nil) {
|
||||
func start(in host: UIView, microphone: MicrophoneChoice, pressedAt: TimeInterval? = nil) {
|
||||
if case .armed(let jobID, let startedAt) = phase {
|
||||
keepArmed(jobID: jobID, startedAt: startedAt)
|
||||
return
|
||||
}
|
||||
guard !isActive else { return }
|
||||
begin(in: host, allowBluetoothMic: allowBluetoothMic, pressedAt: pressedAt, armed: false)
|
||||
begin(in: host, microphone: microphone, pressedAt: pressedAt, armed: false)
|
||||
}
|
||||
|
||||
/// Touch-down on the Hex key: capture starts now, unseen, so the first words aren't lost
|
||||
/// while the touch becomes a tap or a hold (`start` keeps it) or a slide or a cancelled
|
||||
/// touch (`discard` drops it, with nothing transcribed). The microphone opens here.
|
||||
func arm(in host: UIView, allowBluetoothMic: Bool, pressedAt: TimeInterval) {
|
||||
func arm(in host: UIView, microphone: MicrophoneChoice, pressedAt: TimeInterval) {
|
||||
// Without the microphone, the tap's own start says so.
|
||||
guard !isActive, Self.microphoneAllowed else { return }
|
||||
guard let jobID = begin(in: host, allowBluetoothMic: allowBluetoothMic, pressedAt: pressedAt, armed: true) else { return }
|
||||
guard let jobID = begin(in: host, microphone: microphone, pressedAt: pressedAt, armed: true) else { return }
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + Self.armedTimeout) { [weak self] in
|
||||
guard let self, case .armed(let current, _) = self.phase, current == jobID else { return }
|
||||
self.discard(reason: "never kept")
|
||||
@@ -267,7 +268,7 @@ final class KeyboardLocalDictation {
|
||||
|
||||
/// Opens the microphone for a new job, armed (touch-down) or recording; nil when it can't.
|
||||
@discardableResult
|
||||
private func begin(in host: UIView, allowBluetoothMic: Bool, pressedAt: TimeInterval?, armed: Bool) -> String? {
|
||||
private func begin(in host: UIView, microphone: MicrophoneChoice, pressedAt: TimeInterval?, armed: Bool) -> String? {
|
||||
let log = KeyboardProbeLog.shared
|
||||
let appAllowed = KeyboardBridge().appMicrophoneAllowed
|
||||
log.write("start(web\(armed ? ", touch-down" : "")): mic=\(Self.describe(AVAudioApplication.shared.recordPermission)) app=\(appAllowed ? "granted" : "no") speech=\(Self.describe(SFSpeechRecognizer.authorizationStatus())) \(KeyboardProbeLog.memory())")
|
||||
@@ -294,11 +295,10 @@ final class KeyboardLocalDictation {
|
||||
capture.onEvent = { [weak self] event in
|
||||
self?.handle(event, jobID: jobID, requestedAt: requestedAt)
|
||||
}
|
||||
if !allowBluetoothMic {
|
||||
Self.preferBuiltInMicrophone()
|
||||
}
|
||||
let input = Self.microphone(for: microphone)
|
||||
otherAudioAtStart = otherAudioAtStart || AVAudioSession.sharedInstance().isOtherAudioPlaying
|
||||
capture.start(preferBuiltIn: !allowBluetoothMic)
|
||||
// Without a name to ask for, every choice but Bluetooth asks for the iPhone's own.
|
||||
capture.start(microphone: input?.name, builtInFallback: microphone != .bluetooth)
|
||||
return jobID
|
||||
}
|
||||
|
||||
@@ -334,19 +334,28 @@ final class KeyboardLocalDictation {
|
||||
}
|
||||
}
|
||||
|
||||
private static func preferBuiltInMicrophone() {
|
||||
/// The input Settings › Microphone takes on this route (`MicrophoneRoute.capture`), read
|
||||
/// from the keyboard's own session with the category Hex records in: CarPlay's and
|
||||
/// Bluetooth hands-free inputs are listed only there. WebKit records in its own session,
|
||||
/// which only getUserMedia's `deviceId` steers (WebKit then prefers that input), so the
|
||||
/// page asks for this input by its name, the label WebKit gives it.
|
||||
private static func microphone(for choice: MicrophoneChoice) -> Microphone? {
|
||||
let session = AVAudioSession.sharedInstance()
|
||||
do {
|
||||
try session.setCategory(
|
||||
.playAndRecord,
|
||||
mode: .measurement,
|
||||
options: [.mixWithOthers, .allowBluetoothA2DP, .defaultToSpeaker]
|
||||
options: MicrophoneRoute.categoryOptions(allowingBluetooth: choice.allowsBluetooth)
|
||||
)
|
||||
if let builtIn = session.availableInputs?.first(where: { $0.portType == .builtInMic }) {
|
||||
try session.setPreferredInput(builtIn)
|
||||
}
|
||||
let inputs = session.microphones
|
||||
let input = MicrophoneRoute.capture(choice, from: inputs)
|
||||
try? session.prefer(input)
|
||||
let listed = inputs.map { "\($0.name) (\($0.port.rawValue))" }.joined(separator: ", ")
|
||||
KeyboardProbeLog.shared.write("microphone \(choice.rawValue): \(input?.name ?? "none") of [\(listed)]")
|
||||
return input
|
||||
} catch {
|
||||
KeyboardProbeLog.shared.write("built-in mic preference failed: \(describe(error))")
|
||||
KeyboardProbeLog.shared.write("microphone \(choice.rawValue) unknown: \(describe(error))")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,7 +654,7 @@ final class KeyboardLocalDictation {
|
||||
}
|
||||
|
||||
/// What the page timed while starting (wall clock): the device list, the first
|
||||
/// getUserMedia, the stream kept (after a second one for the built-in microphone) and the
|
||||
/// getUserMedia, the stream kept (after a second one for the chosen microphone) and the
|
||||
/// audio context running.
|
||||
struct CaptureSteps {
|
||||
var listedAt: TimeInterval?
|
||||
@@ -788,16 +797,23 @@ private final class KeyboardWebCapture: NSObject, WKNavigationDelegate, WKUIDele
|
||||
webView.loadHTMLString(Self.page, baseURL: URL(string: "https://keyboard.hex.local/"))
|
||||
}
|
||||
|
||||
private var preferBuiltIn = true
|
||||
private var microphone: String?
|
||||
private var builtInFallback = true
|
||||
|
||||
func start(preferBuiltIn: Bool) {
|
||||
self.preferBuiltIn = preferBuiltIn
|
||||
/// Records from the input labelled `microphone` (`KeyboardLocalDictation.microphone(for:)`),
|
||||
/// else, with `builtInFallback`, the iPhone's own microphone, else WebKit's default.
|
||||
func start(microphone: String?, builtInFallback: Bool) {
|
||||
self.microphone = microphone
|
||||
self.builtInFallback = builtInFallback
|
||||
guard isLoaded else {
|
||||
startWhenLoaded = true
|
||||
return
|
||||
}
|
||||
scriptAt = Date().timeIntervalSince1970
|
||||
webView.evaluateJavaScript("hexStart(\(preferBuiltIn))")
|
||||
let label = microphone
|
||||
.flatMap { try? JSONEncoder().encode($0) }
|
||||
.flatMap { String(data: $0, encoding: .utf8) } ?? "null"
|
||||
webView.evaluateJavaScript("hexStart(\(label), \(builtInFallback))")
|
||||
}
|
||||
|
||||
func stop() {
|
||||
@@ -823,7 +839,7 @@ private final class KeyboardWebCapture: NSObject, WKNavigationDelegate, WKUIDele
|
||||
onEvent?(.loaded)
|
||||
if startWhenLoaded {
|
||||
startWhenLoaded = false
|
||||
start(preferBuiltIn: preferBuiltIn)
|
||||
start(microphone: microphone, builtInFallback: builtInFallback)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -877,12 +893,15 @@ private final class KeyboardWebCapture: NSObject, WKNavigationDelegate, WKUIDele
|
||||
if (c) c.close().catch(() => {});
|
||||
};
|
||||
const base = { channelCount: 1, echoCancellation: false, noiseSuppression: false, autoGainControl: false };
|
||||
async function builtInMicrophone() {
|
||||
// The input named `label`, else (with `builtIn`) the iPhone's own. Labels stay empty
|
||||
// until this page has had the microphone once.
|
||||
async function chosenMicrophone(label, builtIn) {
|
||||
const inputs = (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "audioinput");
|
||||
const found = inputs.find((d) => /iphone|ipad|built-in/i.test(d.label));
|
||||
const found = (label && inputs.find((d) => d.label === label))
|
||||
|| (builtIn && inputs.find((d) => /iphone|ipad|built-in/i.test(d.label)));
|
||||
return found ? found.deviceId : null;
|
||||
}
|
||||
async function hexStart(preferBuiltIn) {
|
||||
async function hexStart(label, builtIn) {
|
||||
if (running) return;
|
||||
running = true;
|
||||
// A hexStop while this start waits (a slide off the Hex key right after touch-down)
|
||||
@@ -891,14 +910,15 @@ private final class KeyboardWebCapture: NSObject, WKNavigationDelegate, WKUIDele
|
||||
const stale = () => start !== generation;
|
||||
let s = null, c = null;
|
||||
try {
|
||||
let id = preferBuiltIn ? await builtInMicrophone() : null;
|
||||
const choosing = !!label || builtIn;
|
||||
let id = choosing ? await chosenMicrophone(label, builtIn) : null;
|
||||
if (stale()) return;
|
||||
const listed = Date.now();
|
||||
s = await navigator.mediaDevices.getUserMedia({ audio: id ? { ...base, deviceId: { exact: id } } : base });
|
||||
if (stale()) return release(s);
|
||||
const opened = Date.now();
|
||||
if (preferBuiltIn && !id) {
|
||||
id = await builtInMicrophone();
|
||||
if (choosing && !id) {
|
||||
id = await chosenMicrophone(label, builtIn);
|
||||
if (stale()) return release(s);
|
||||
if (id && s.getAudioTracks()[0].getSettings().deviceId !== id) {
|
||||
s.getTracks().forEach((t) => t.stop());
|
||||
|
||||
@@ -941,7 +941,7 @@ final class KeyboardViewController: UIInputViewController {
|
||||
guard let self else { return }
|
||||
self.localDictation.start(
|
||||
in: self.view,
|
||||
allowBluetoothMic: self.bridge.allowBluetoothMic,
|
||||
microphone: self.bridge.microphone,
|
||||
pressedAt: self.takeHexKeyPress()
|
||||
)
|
||||
} : nil
|
||||
@@ -1120,7 +1120,7 @@ final class KeyboardViewController: UIInputViewController {
|
||||
hexKeyPressedAt = time
|
||||
guard viewModel.hasFullAccess, !viewModel.isWarmAvailable, viewModel.onLocalDictateTap != nil,
|
||||
viewModel.stagePhase == .idle || viewModel.stagePhase == .failed else { return }
|
||||
localDictation.arm(in: view, allowBluetoothMic: bridge.allowBluetoothMic, pressedAt: time)
|
||||
localDictation.arm(in: view, microphone: bridge.microphone, pressedAt: time)
|
||||
}
|
||||
|
||||
/// The touch-down that led to this start, if it was the Hex key's in the last 2 s.
|
||||
|
||||
@@ -32,10 +32,12 @@ protocol AudioManaging: AnyObject {
|
||||
var onUnexpectedCaptureEnd: ((URL, Bool) -> Void)? { get set }
|
||||
|
||||
func requestPermission() async -> Bool
|
||||
func startKeepalive(allowBluetooth: Bool) throws
|
||||
/// Holds the iPhone's microphone between dictations (`MicrophoneRoute.keepalive`).
|
||||
func startKeepalive() throws
|
||||
func stopKeepalive()
|
||||
func deactivateSession()
|
||||
func beginCapture(at url: URL, maxDuration: TimeInterval, allowBluetooth: Bool) throws -> any ActiveAudioCapture
|
||||
/// Records from `microphone`'s input for this route (`MicrophoneRoute.capture`).
|
||||
func beginCapture(at url: URL, maxDuration: TimeInterval, microphone: MicrophoneChoice) throws -> any ActiveAudioCapture
|
||||
}
|
||||
|
||||
/// Keeps AVAudioRecorders that stopped or failed to start alive until their audio queue is
|
||||
@@ -161,11 +163,11 @@ final class SystemAudioManager: AudioManaging {
|
||||
}
|
||||
}
|
||||
|
||||
func startKeepalive(allowBluetooth: Bool) throws {
|
||||
func startKeepalive() throws {
|
||||
stopKeepalive()
|
||||
try configureAudioSession(allowBluetooth: allowBluetooth)
|
||||
try configureAudioSession(recordingFrom: nil)
|
||||
|
||||
// Changing the session (Always use iPhone microphone, or a route change) can move the
|
||||
// Changing the session (a dictation's own input, or a route change) can move the
|
||||
// hardware to another sample rate. An engine built before that keeps the old input
|
||||
// format, and installTap raises an Objective-C exception Swift can't catch, so build a
|
||||
// fresh engine for the current route and tap with the format the hardware reports.
|
||||
@@ -214,10 +216,10 @@ final class SystemAudioManager: AudioManaging {
|
||||
func beginCapture(
|
||||
at url: URL,
|
||||
maxDuration: TimeInterval,
|
||||
allowBluetooth: Bool
|
||||
microphone: MicrophoneChoice
|
||||
) throws -> any ActiveAudioCapture {
|
||||
stopKeepalive()
|
||||
try configureAudioSession(allowBluetooth: allowBluetooth)
|
||||
try configureAudioSession(recordingFrom: microphone)
|
||||
|
||||
let settings: [String: Any] = [
|
||||
AVFormatIDKey: kAudioFormatLinearPCM,
|
||||
@@ -246,27 +248,31 @@ final class SystemAudioManager: AudioManaging {
|
||||
|
||||
/// Captures and the warm keepalive record alongside other audio: `.mixWithOthers` never
|
||||
/// interrupts another app, so its video or music keeps playing (over A2DP in a car or
|
||||
/// headphones) with nothing to resume, and no `.duckOthers`. Always use iPhone microphone
|
||||
/// (the default) records from the iPhone's microphone; turned off, a Bluetooth headset's
|
||||
/// hands-free microphone is allowed too (iOS routes HFP first when a device has both).
|
||||
/// headphones) with nothing to resume, and no `.duckOthers`.
|
||||
///
|
||||
/// A dictation records from Settings › Microphone's input for this route
|
||||
/// (`MicrophoneRoute.capture`): with Automatic (the default) a wired headset's
|
||||
/// microphone, the car's in CarPlay, else the iPhone's; Bluetooth hands-free microphones
|
||||
/// only with Bluetooth, the one choice that adds `.allowBluetoothHFP`. The keepalive
|
||||
/// (`choice` nil) stays on the iPhone's microphone without HFP, so a warm session never
|
||||
/// holds a car or headset in call audio between dictations. The input is always set,
|
||||
/// never left to an earlier preference or to iOS, which routes HFP and CarPlay first.
|
||||
///
|
||||
/// No preferred sample rate: `.playAndRecord` runs the microphone and the output at one
|
||||
/// hardware rate, so asking for 16 kHz moved everything the iPhone played and recorded (a
|
||||
/// screen recording's audio too) to 16 kHz for as long as Hex held the session, and back
|
||||
/// at its end. The hardware keeps its own rate: the recorder writes 16 kHz itself, and the
|
||||
/// keepalive taps whatever format the hardware reports.
|
||||
func configureAudioSession(allowBluetooth: Bool) throws {
|
||||
func configureAudioSession(recordingFrom choice: MicrophoneChoice?) throws {
|
||||
try session.setCategory(
|
||||
.playAndRecord,
|
||||
mode: .measurement,
|
||||
options: allowBluetooth
|
||||
? [.mixWithOthers, .allowBluetoothHFP, .allowBluetoothA2DP, .defaultToSpeaker]
|
||||
: [.mixWithOthers, .allowBluetoothA2DP, .defaultToSpeaker]
|
||||
options: MicrophoneRoute.categoryOptions(allowingBluetooth: choice?.allowsBluetooth ?? false)
|
||||
)
|
||||
try session.setActive(true, options: [])
|
||||
if !allowBluetooth, let builtIn = session.availableInputs?.first(where: { $0.portType == .builtInMic }) {
|
||||
try? session.setPreferredInput(builtIn)
|
||||
}
|
||||
let inputs = session.microphones
|
||||
let input = choice.map { MicrophoneRoute.capture($0, from: inputs) } ?? MicrophoneRoute.keepalive(from: inputs)
|
||||
try? session.prefer(input)
|
||||
}
|
||||
|
||||
nonisolated private static func discardSamples(
|
||||
|
||||
@@ -166,7 +166,7 @@ final class DictationController {
|
||||
@ObservationIgnored private var lastPublishedSnapshotAt: TimeInterval = -100
|
||||
var warmDuration: WarmSessionDuration
|
||||
private(set) var style: DictationStyle
|
||||
private(set) var allowBluetoothMic: Bool
|
||||
private(set) var microphone: MicrophoneChoice
|
||||
private(set) var handoffNotice: String?
|
||||
var engineName = "Local speech"
|
||||
var transcriptionLanguage = "English"
|
||||
@@ -241,7 +241,7 @@ final class DictationController {
|
||||
self.followedKeyboardLanguage = languageSettings.keyboardDictationLanguage()
|
||||
self.warmDuration = resolvedBridge.warmDuration
|
||||
self.style = resolvedBridge.style
|
||||
self.allowBluetoothMic = resolvedBridge.allowBluetoothMic
|
||||
self.microphone = resolvedBridge.microphone
|
||||
|
||||
let hasCachedModel = ParakeetTranscriber.hasCachedModel
|
||||
resolvedBridge.publish(.offline)
|
||||
@@ -393,13 +393,12 @@ final class DictationController {
|
||||
}
|
||||
}
|
||||
|
||||
func setAllowBluetoothMic(_ allow: Bool) {
|
||||
guard allowBluetoothMic != allow else { return }
|
||||
allowBluetoothMic = allow
|
||||
keyboardBridge.allowBluetoothMic = allow
|
||||
if keyboardSessionEnabled, phase == .ready {
|
||||
try? audio.startKeepalive(allowBluetooth: allow)
|
||||
}
|
||||
/// The next dictation records from the new choice's input; the warm keepalive stays on
|
||||
/// the iPhone's microphone whatever the choice.
|
||||
func setMicrophone(_ choice: MicrophoneChoice) {
|
||||
guard microphone != choice else { return }
|
||||
microphone = choice
|
||||
keyboardBridge.microphone = choice
|
||||
}
|
||||
|
||||
// MARK: - Standalone & System Actions
|
||||
@@ -669,7 +668,7 @@ final class DictationController {
|
||||
}
|
||||
|
||||
do {
|
||||
try audio.startKeepalive(allowBluetooth: allowBluetoothMic)
|
||||
try audio.startKeepalive()
|
||||
enableWarmSessionBookkeeping()
|
||||
phase = .ready
|
||||
startKeyboardSessionLoop()
|
||||
@@ -865,7 +864,7 @@ final class DictationController {
|
||||
let capture = try audio.beginCapture(
|
||||
at: captureURL,
|
||||
maxDuration: Self.maxCaptureDuration,
|
||||
allowBluetooth: allowBluetoothMic
|
||||
microphone: microphone
|
||||
)
|
||||
guard self.jobGeneration == captureGeneration else {
|
||||
capture.stop()
|
||||
@@ -1080,7 +1079,7 @@ final class DictationController {
|
||||
return
|
||||
}
|
||||
do {
|
||||
try audio.startKeepalive(allowBluetooth: allowBluetoothMic)
|
||||
try audio.startKeepalive()
|
||||
} catch {
|
||||
keyboardSessionEnabled = false
|
||||
keyboardSessionRemaining = 0
|
||||
@@ -1172,7 +1171,7 @@ final class DictationController {
|
||||
} else if self.phase == .ready && !self.suspendedWarmSessionOnInterruption,
|
||||
self.keepaliveRestartIsDue() {
|
||||
do {
|
||||
try self.audio.startKeepalive(allowBluetooth: self.allowBluetoothMic)
|
||||
try self.audio.startKeepalive()
|
||||
} catch {
|
||||
self.endWarmSession()
|
||||
return
|
||||
@@ -1365,7 +1364,7 @@ final class DictationController {
|
||||
}
|
||||
if shouldResume || UIApplication.shared.applicationState == .active {
|
||||
do {
|
||||
try audio.startKeepalive(allowBluetooth: allowBluetoothMic)
|
||||
try audio.startKeepalive()
|
||||
publishKeyboardSnapshot()
|
||||
} catch {
|
||||
endWarmSession()
|
||||
@@ -1384,7 +1383,7 @@ final class DictationController {
|
||||
}
|
||||
} else if keyboardSessionEnabled && phase == .ready {
|
||||
do {
|
||||
try audio.startKeepalive(allowBluetooth: allowBluetoothMic)
|
||||
try audio.startKeepalive()
|
||||
publishKeyboardSnapshot()
|
||||
} catch {
|
||||
endWarmSession()
|
||||
@@ -1392,8 +1391,10 @@ final class DictationController {
|
||||
}
|
||||
|
||||
case .routeNewDeviceAvailable:
|
||||
if keyboardSessionEnabled && phase == .ready && allowBluetoothMic {
|
||||
try? audio.startKeepalive(allowBluetooth: allowBluetoothMic)
|
||||
// A headset or car that just connected can take the input: the keepalive goes back
|
||||
// to the iPhone's microphone, on a fresh engine for the route's format.
|
||||
if keyboardSessionEnabled && phase == .ready {
|
||||
try? audio.startKeepalive()
|
||||
publishKeyboardSnapshot()
|
||||
}
|
||||
|
||||
@@ -1403,7 +1404,7 @@ final class DictationController {
|
||||
}
|
||||
if keyboardSessionEnabled {
|
||||
do {
|
||||
try audio.startKeepalive(allowBluetooth: allowBluetoothMic)
|
||||
try audio.startKeepalive()
|
||||
publishKeyboardSnapshot()
|
||||
} catch {
|
||||
endWarmSession()
|
||||
|
||||
@@ -527,6 +527,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"AirPods and car mics, in call quality" : {
|
||||
"localizations" : {
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "也用 AirPods 和车载麦克风(通话音质)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Alex" : {
|
||||
"shouldTranslate" : false
|
||||
},
|
||||
@@ -570,16 +580,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"Always use iPhone microphone" : {
|
||||
"localizations" : {
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "始终使用 iPhone 麦克风"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"An emoji key on the dictation bar" : {
|
||||
"localizations" : {
|
||||
"zh-Hans" : {
|
||||
@@ -720,6 +720,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"Bluetooth" : {
|
||||
"localizations" : {
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "蓝牙"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Cancel" : {
|
||||
"localizations" : {
|
||||
"zh-Hans" : {
|
||||
@@ -750,6 +760,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"Car mic in CarPlay, else iPhone mic" : {
|
||||
"localizations" : {
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "CarPlay 中用车载麦克风,其余用 iPhone"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Casual" : {
|
||||
"localizations" : {
|
||||
"zh-Hans" : {
|
||||
@@ -1423,6 +1443,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"iPhone" : {
|
||||
"localizations" : {
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "iPhone"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Keep mic warm" : {
|
||||
"localizations" : {
|
||||
"zh-Hans" : {
|
||||
|
||||
@@ -115,14 +115,32 @@ struct DictationSettingsPage: View {
|
||||
|
||||
SettingsDivider()
|
||||
|
||||
SettingsToggleRow(
|
||||
title: String(localized: "Always use iPhone microphone"),
|
||||
detail: String(localized: "Keeps music playing and starts faster"),
|
||||
isOn: Binding(
|
||||
get: { !dictation.allowBluetoothMic },
|
||||
set: { dictation.setAllowBluetoothMic(!$0) }
|
||||
// With a car, headset or headphones connected (`MicrophoneRoute`).
|
||||
HStack(spacing: 12) {
|
||||
SettingsRowLabel(
|
||||
title: String(localized: "Microphone"),
|
||||
detail: dictation.microphone.detail
|
||||
)
|
||||
)
|
||||
Spacer(minLength: 8)
|
||||
Menu {
|
||||
ForEach(MicrophoneChoice.allCases, id: \.self) { candidate in
|
||||
Button {
|
||||
dictation.setMicrophone(candidate)
|
||||
} label: {
|
||||
if dictation.microphone == candidate {
|
||||
Label(candidate.label, systemImage: "checkmark")
|
||||
} else {
|
||||
Text(candidate.label)
|
||||
}
|
||||
}
|
||||
}
|
||||
} label: {
|
||||
SettingsMenuValue(value: dictation.microphone.label)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 10)
|
||||
.frame(minHeight: 50)
|
||||
}
|
||||
}
|
||||
.animation(HexMotion.settleAnimation(reduceMotion: reduceMotion), value: customVocabulary)
|
||||
|
||||
@@ -39,6 +39,8 @@ private final class FakeAudioManager: AudioManaging {
|
||||
var deactivateCount = 0
|
||||
var createdCaptures: [FakeAudioCapture] = []
|
||||
var keepaliveStarts = 0
|
||||
/// The Settings › Microphone choice each capture was asked to record from.
|
||||
var captureMicrophones: [MicrophoneChoice] = []
|
||||
/// An engine that stops again by itself as soon as it starts.
|
||||
var keepaliveStopsRightAway = false
|
||||
|
||||
@@ -49,7 +51,7 @@ private final class FakeAudioManager: AudioManaging {
|
||||
permissionGranted
|
||||
}
|
||||
|
||||
func startKeepalive(allowBluetooth: Bool) throws {
|
||||
func startKeepalive() throws {
|
||||
keepaliveStarts += 1
|
||||
if keepaliveShouldThrow {
|
||||
isKeepaliveRunning = false
|
||||
@@ -70,8 +72,9 @@ private final class FakeAudioManager: AudioManaging {
|
||||
func beginCapture(
|
||||
at url: URL,
|
||||
maxDuration: TimeInterval,
|
||||
allowBluetooth: Bool
|
||||
microphone: MicrophoneChoice
|
||||
) throws -> any ActiveAudioCapture {
|
||||
captureMicrophones.append(microphone)
|
||||
isKeepaliveRunning = false
|
||||
if captureShouldThrow {
|
||||
throw CocoaError(.fileWriteUnknown)
|
||||
@@ -250,6 +253,37 @@ final class DictationControllerTests: XCTestCase {
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: secondCaptureURL.path))
|
||||
}
|
||||
|
||||
func testDictationRecordsFromTheMicrophoneChosenInSettings() async throws {
|
||||
let audio = FakeAudioManager()
|
||||
let transcriber = ControlledTranscriber()
|
||||
let bridge = KeyboardBridge(defaults: defaults)
|
||||
let controller = DictationController(
|
||||
audio: audio,
|
||||
keyboardBridge: bridge,
|
||||
transcriber: transcriber,
|
||||
transcriberFactory: { transcriber },
|
||||
now: { 1_500 },
|
||||
autoPrepareOnInit: false
|
||||
)
|
||||
controller.prepareModel()
|
||||
try await settle()
|
||||
XCTAssertEqual(controller.microphone, .automatic)
|
||||
|
||||
controller.startRecording(keyboardJobID: "job-a")
|
||||
try await settle()
|
||||
XCTAssertEqual(controller.phase, .recording)
|
||||
controller.cancelCurrentJob()
|
||||
|
||||
controller.setMicrophone(.bluetooth)
|
||||
XCTAssertEqual(bridge.microphone, .bluetooth, "the keyboard's capture page follows it too")
|
||||
controller.startRecording(keyboardJobID: "job-b")
|
||||
try await settle()
|
||||
XCTAssertEqual(controller.phase, .recording)
|
||||
controller.cancelCurrentJob()
|
||||
|
||||
XCTAssertEqual(audio.captureMicrophones, [.automatic, .bluetooth])
|
||||
}
|
||||
|
||||
func testAcceptedJobDeliversTranscriptEvenWhenWarmSessionCloses() async throws {
|
||||
let now = 2_000.0
|
||||
let audio = FakeAudioManager()
|
||||
@@ -2205,13 +2239,19 @@ final class AppleSpeechClipTests: XCTestCase {
|
||||
private final class FakeAudioSession: AudioSessionControlling {
|
||||
enum Call: Equatable {
|
||||
case category(AVAudioSession.Category, AVAudioSession.Mode, AVAudioSession.CategoryOptions)
|
||||
case preferredInput
|
||||
case preferredInput(AVAudioSession.Port?)
|
||||
case active(Bool, AVAudioSession.SetActiveOptions)
|
||||
}
|
||||
|
||||
var calls: [Call] = []
|
||||
var isOtherAudioPlaying = false
|
||||
var availableInputs: [AVAudioSessionPortDescription]? { nil }
|
||||
/// What iOS offers: Bluetooth hands-free inputs only in a category that allows them.
|
||||
var connected: [Microphone] = []
|
||||
private var allowsBluetooth = false
|
||||
|
||||
var microphones: [Microphone] {
|
||||
connected.filter { allowsBluetooth || ($0.port != .bluetoothHFP && $0.port != .bluetoothLE) }
|
||||
}
|
||||
|
||||
func setCategory(
|
||||
_ category: AVAudioSession.Category,
|
||||
@@ -2219,10 +2259,11 @@ private final class FakeAudioSession: AudioSessionControlling {
|
||||
options: AVAudioSession.CategoryOptions
|
||||
) throws {
|
||||
calls.append(.category(category, mode, options))
|
||||
allowsBluetooth = options.contains(.allowBluetoothHFP)
|
||||
}
|
||||
|
||||
func setPreferredInput(_ inPort: AVAudioSessionPortDescription?) throws {
|
||||
calls.append(.preferredInput)
|
||||
func prefer(_ microphone: Microphone?) throws {
|
||||
calls.append(.preferredInput(microphone?.port))
|
||||
}
|
||||
|
||||
func setActive(_ active: Bool, options: AVAudioSession.SetActiveOptions) throws {
|
||||
@@ -2230,13 +2271,20 @@ private final class FakeAudioSession: AudioSessionControlling {
|
||||
}
|
||||
}
|
||||
|
||||
private let iPhoneMic = Microphone(uid: "Built-In Microphone", name: "iPhone Microphone", port: .builtInMic)
|
||||
private let airPods = Microphone(uid: "A0:B1:C2:D3:E4:F5-tsco", name: "AirPods Pro", port: .bluetoothHFP)
|
||||
private let bluetoothCar = Microphone(uid: "10:20:30:40:50:60-tsco", name: "My Car", port: .bluetoothHFP)
|
||||
private let carPlay = Microphone(uid: "CarPlay-mic", name: "CarPlay", port: .carAudio)
|
||||
private let wiredHeadset = Microphone(uid: "Wired Headset Microphone", name: "Headset Microphone", port: .headsetMic)
|
||||
|
||||
@MainActor
|
||||
final class AudioSessionSetupTests: XCTestCase {
|
||||
func testRecordingMixesWithOtherAppsAudioWithOrWithoutTheBluetoothMicrophone() throws {
|
||||
for allowBluetooth in [false, true] {
|
||||
func testRecordingMixesWithOtherAppsAudioWhateverTheMicrophone() throws {
|
||||
let choices: [MicrophoneChoice?] = [nil] + MicrophoneChoice.allCases.map { $0 }
|
||||
for choice in choices {
|
||||
let session = FakeAudioSession()
|
||||
let audio = SystemAudioManager(session: session)
|
||||
try audio.configureAudioSession(allowBluetooth: allowBluetooth)
|
||||
try audio.configureAudioSession(recordingFrom: choice)
|
||||
|
||||
guard case .category(let category, let mode, let options)? = session.calls.first else {
|
||||
return XCTFail("the category is set first")
|
||||
@@ -2246,26 +2294,81 @@ final class AudioSessionSetupTests: XCTestCase {
|
||||
XCTAssertTrue(options.contains(.mixWithOthers), "never interrupts another app's video or music")
|
||||
XCTAssertFalse(options.contains(.duckOthers))
|
||||
XCTAssertTrue(options.contains(.allowBluetoothA2DP))
|
||||
XCTAssertEqual(options.contains(.allowBluetoothHFP), allowBluetooth, "the Bluetooth microphone only when allowed")
|
||||
XCTAssertEqual(session.calls.last, .active(true, []))
|
||||
XCTAssertEqual(
|
||||
options.contains(.allowBluetoothHFP), choice == .bluetooth,
|
||||
"Bluetooth hands-free microphones only for a dictation with Bluetooth chosen, never the keepalive"
|
||||
)
|
||||
XCTAssertEqual(session.calls[1], .active(true, []))
|
||||
}
|
||||
}
|
||||
|
||||
/// Ryan's car: in CarPlay, Automatic (the default) records from the car's microphone, not
|
||||
/// the iPhone in its cupholder hearing the speakers. AirPods keep the iPhone's microphone
|
||||
/// (music stays at full quality, nothing waits for call audio); Bluetooth takes theirs.
|
||||
func testEachChoiceRecordsFromItsMicrophoneForTheRoute() {
|
||||
let routes: [(String, [Microphone], [MicrophoneChoice: Microphone])] = [
|
||||
("nothing connected", [iPhoneMic], [.automatic: iPhoneMic, .iPhone: iPhoneMic, .bluetooth: iPhoneMic]),
|
||||
("CarPlay", [iPhoneMic, carPlay], [.automatic: carPlay, .iPhone: iPhoneMic, .bluetooth: carPlay]),
|
||||
("AirPods", [iPhoneMic, airPods], [.automatic: iPhoneMic, .iPhone: iPhoneMic, .bluetooth: airPods]),
|
||||
("a Bluetooth car kit", [iPhoneMic, bluetoothCar], [.automatic: iPhoneMic, .iPhone: iPhoneMic, .bluetooth: bluetoothCar]),
|
||||
("a wired headset", [iPhoneMic, wiredHeadset], [.automatic: wiredHeadset, .iPhone: iPhoneMic, .bluetooth: wiredHeadset]),
|
||||
]
|
||||
for (route, inputs, expected) in routes {
|
||||
for (choice, input) in expected {
|
||||
XCTAssertEqual(MicrophoneRoute.capture(choice, from: inputs), input, "\(choice) with \(route)")
|
||||
}
|
||||
XCTAssertEqual(MicrophoneRoute.keepalive(from: inputs), iPhoneMic, "the keepalive with \(route)")
|
||||
}
|
||||
}
|
||||
|
||||
func testTheSessionPrefersTheChosenInputAndTheKeepaliveTheIPhones() throws {
|
||||
let cases: [(MicrophoneChoice?, [Microphone], AVAudioSession.Port)] = [
|
||||
(.automatic, [iPhoneMic, carPlay], .carAudio),
|
||||
(.iPhone, [iPhoneMic, carPlay], .builtInMic),
|
||||
(.bluetooth, [iPhoneMic, airPods], .bluetoothHFP),
|
||||
(.automatic, [iPhoneMic, airPods], .builtInMic),
|
||||
// A warm session between dictations never holds the car or headset in call audio.
|
||||
(nil, [iPhoneMic, carPlay], .builtInMic),
|
||||
(nil, [iPhoneMic, airPods], .builtInMic),
|
||||
]
|
||||
for (choice, connected, port) in cases {
|
||||
let session = FakeAudioSession()
|
||||
session.connected = connected
|
||||
try SystemAudioManager(session: session).configureAudioSession(recordingFrom: choice)
|
||||
XCTAssertEqual(session.calls.last, .preferredInput(port), "\(String(describing: choice)) with \(connected.map(\.name))")
|
||||
}
|
||||
}
|
||||
|
||||
func testTheMicrophoneChoiceDefaultsToAutomaticAndKeepsAnOldBluetoothSwitch() throws {
|
||||
let suite = "hex.tests.\(UUID().uuidString)"
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
let bridge = KeyboardBridge(defaults: defaults)
|
||||
XCTAssertEqual(bridge.microphone, .automatic, "Always use iPhone microphone left on, its default")
|
||||
|
||||
defaults.set(true, forKey: "settings.allowBluetoothMic")
|
||||
XCTAssertEqual(bridge.microphone, .bluetooth, "Always use iPhone microphone turned off")
|
||||
|
||||
bridge.microphone = .iPhone
|
||||
XCTAssertEqual(KeyboardBridge(defaults: defaults).microphone, .iPhone)
|
||||
}
|
||||
|
||||
/// `.playAndRecord` runs the microphone and the output at one rate: a preferred 16 kHz
|
||||
/// moved everything the iPhone played and recorded, a screen recording's audio too, to
|
||||
/// 16 kHz while Hex held the session (the simulator went from 48 kHz to 16 kHz).
|
||||
func testRecordingLeavesTheHardwareAtItsOwnSampleRate() throws {
|
||||
let session = FakeAudioSession()
|
||||
try SystemAudioManager(session: session).configureAudioSession(allowBluetooth: false)
|
||||
try SystemAudioManager(session: session).configureAudioSession(recordingFrom: .automatic)
|
||||
XCTAssertEqual(session.calls, [
|
||||
.category(.playAndRecord, .measurement, [.mixWithOthers, .allowBluetoothA2DP, .defaultToSpeaker]),
|
||||
.active(true, []),
|
||||
.preferredInput(nil),
|
||||
], "no preferred sample rate")
|
||||
|
||||
let shared = AVAudioSession.sharedInstance()
|
||||
let before = shared.sampleRate
|
||||
do {
|
||||
try SystemAudioManager().configureAudioSession(allowBluetooth: false)
|
||||
try SystemAudioManager().configureAudioSession(recordingFrom: .automatic)
|
||||
} catch {
|
||||
throw XCTSkip("No audio session to activate here: \(error)")
|
||||
}
|
||||
|
||||
@@ -3,17 +3,29 @@ import AVFAudio
|
||||
/// The `AVAudioSession` calls Hex makes, so tests can check how it records and lets go.
|
||||
protocol AudioSessionControlling: AnyObject {
|
||||
var isOtherAudioPlaying: Bool { get }
|
||||
var availableInputs: [AVAudioSessionPortDescription]? { get }
|
||||
/// The inputs the current category offers.
|
||||
var microphones: [Microphone] { get }
|
||||
func setCategory(
|
||||
_ category: AVAudioSession.Category,
|
||||
mode: AVAudioSession.Mode,
|
||||
options: AVAudioSession.CategoryOptions
|
||||
) throws
|
||||
func setPreferredInput(_ inPort: AVAudioSessionPortDescription?) throws
|
||||
/// Records from `microphone`, or from iOS's choice for nil.
|
||||
func prefer(_ microphone: Microphone?) throws
|
||||
func setActive(_ active: Bool, options: AVAudioSession.SetActiveOptions) throws
|
||||
}
|
||||
|
||||
extension AVAudioSession: AudioSessionControlling {}
|
||||
extension AVAudioSession: AudioSessionControlling {
|
||||
var microphones: [Microphone] {
|
||||
(availableInputs ?? []).map(Microphone.init)
|
||||
}
|
||||
|
||||
func prefer(_ microphone: Microphone?) throws {
|
||||
try setPreferredInput(microphone.flatMap { wanted in
|
||||
availableInputs?.first { $0.uid == wanted.uid }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Lets other apps' audio that in-keyboard dictation interrupted play again.
|
||||
///
|
||||
|
||||
@@ -417,6 +417,9 @@ struct KeyboardBridge {
|
||||
static let snapshot = "keyboard.snapshot"
|
||||
static let warmDuration = "settings.warmDuration"
|
||||
static let style = "settings.dictationStyle"
|
||||
static let microphone = "settings.microphone"
|
||||
/// Before Settings › Microphone: true allowed Bluetooth microphones (Always use iPhone
|
||||
/// microphone off). Read only while Microphone is unset.
|
||||
static let allowBluetoothMic = "settings.allowBluetoothMic"
|
||||
static let lastInsertedResultID = "keyboard.lastInsertedResultID"
|
||||
static let fullAccessSeenAt = "keyboard.fullAccessSeenAt"
|
||||
@@ -490,12 +493,17 @@ struct KeyboardBridge {
|
||||
}
|
||||
}
|
||||
|
||||
var allowBluetoothMic: Bool {
|
||||
/// Settings › Microphone. Unset, it is Automatic, or Bluetooth for someone who turned off
|
||||
/// Always use iPhone microphone (the switch it replaced).
|
||||
var microphone: MicrophoneChoice {
|
||||
get {
|
||||
defaults?.bool(forKey: Key.allowBluetoothMic) ?? false
|
||||
if let raw = defaults?.string(forKey: Key.microphone), let choice = MicrophoneChoice(rawValue: raw) {
|
||||
return choice
|
||||
}
|
||||
return defaults?.bool(forKey: Key.allowBluetoothMic) == true ? .bluetooth : .automatic
|
||||
}
|
||||
nonmutating set {
|
||||
defaults?.set(newValue, forKey: Key.allowBluetoothMic)
|
||||
defaults?.set(newValue.rawValue, forKey: Key.microphone)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import AVFAudio
|
||||
|
||||
/// Settings › Dictation › Microphone: what dictation records from while a car, headset or
|
||||
/// headphones are connected. The app's recorder and the keyboard's capture page both follow it.
|
||||
nonisolated enum MicrophoneChoice: String, CaseIterable, Sendable {
|
||||
/// A wired or USB headset's microphone, the car's in CarPlay, otherwise the iPhone's:
|
||||
/// Bluetooth headphones keep playing at full quality, and nothing waits for call audio.
|
||||
case automatic
|
||||
/// Always the iPhone's own microphone.
|
||||
case iPhone
|
||||
/// Bluetooth hands-free microphones too: AirPods, headsets and Bluetooth car kits, which
|
||||
/// switch to call audio (8–16 kHz, other audio in call quality) while dictating.
|
||||
case bluetooth
|
||||
|
||||
var label: String {
|
||||
switch self {
|
||||
case .automatic: String(localized: "Automatic")
|
||||
case .iPhone: String(localized: "iPhone")
|
||||
case .bluetooth: String(localized: "Bluetooth")
|
||||
}
|
||||
}
|
||||
|
||||
var detail: String {
|
||||
switch self {
|
||||
case .automatic: String(localized: "Car mic in CarPlay, else iPhone mic")
|
||||
case .iPhone: String(localized: "Keeps music playing and starts faster")
|
||||
case .bluetooth: String(localized: "AirPods and car mics, in call quality")
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a capture may record from a Bluetooth hands-free microphone, which needs
|
||||
/// `.allowBluetoothHFP` in the session's category.
|
||||
var allowsBluetooth: Bool { self == .bluetooth }
|
||||
}
|
||||
|
||||
/// An input iOS offers (`AVAudioSessionPortDescription`), as a value tests can make.
|
||||
nonisolated struct Microphone: Equatable, Sendable {
|
||||
let uid: String
|
||||
let name: String
|
||||
let port: AVAudioSession.Port
|
||||
|
||||
init(uid: String, name: String, port: AVAudioSession.Port) {
|
||||
self.uid = uid
|
||||
self.name = name
|
||||
self.port = port
|
||||
}
|
||||
|
||||
init(_ description: AVAudioSessionPortDescription) {
|
||||
self.init(uid: description.uid, name: description.portName, port: description.portType)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of the inputs iOS offers a dictation and the warm session record from.
|
||||
nonisolated enum MicrophoneRoute {
|
||||
/// The input a dictation records from; nil when none of the choice's kinds is offered.
|
||||
///
|
||||
/// Automatic takes a wired or USB headset's microphone (close to the mouth, no call audio)
|
||||
/// and, in CarPlay, the car's: the one the car has for its driver, which Siri and calls
|
||||
/// use, where the iPhone's would hear the car's speakers and the road. A Bluetooth car kit
|
||||
/// can't be told from headphones, so it takes `bluetooth`.
|
||||
static func capture(_ choice: MicrophoneChoice, from inputs: [Microphone]) -> Microphone? {
|
||||
let order: [AVAudioSession.Port] = switch choice {
|
||||
case .iPhone: [.builtInMic]
|
||||
case .automatic: [.headsetMic, .usbAudio, .carAudio, .builtInMic]
|
||||
case .bluetooth: [.headsetMic, .usbAudio, .carAudio, .bluetoothHFP, .bluetoothLE, .builtInMic]
|
||||
}
|
||||
for port in order {
|
||||
if let input = inputs.first(where: { $0.port == port }) { return input }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// The warm session's keepalive, which holds the microphone between dictations: always the
|
||||
/// iPhone's, so a warm session never keeps a car or headset in call audio for its minutes.
|
||||
/// Each dictation moves to its own input as it starts.
|
||||
static func keepalive(from inputs: [Microphone]) -> Microphone? {
|
||||
inputs.first { $0.port == .builtInMic }
|
||||
}
|
||||
|
||||
/// The category options for recording: `.mixWithOthers` keeps other apps' video and music
|
||||
/// playing, and A2DP keeps headphones in stereo while another microphone records.
|
||||
/// Bluetooth hands-free inputs are offered only when allowed.
|
||||
static func categoryOptions(allowingBluetooth: Bool) -> AVAudioSession.CategoryOptions {
|
||||
allowingBluetooth
|
||||
? [.mixWithOthers, .allowBluetoothHFP, .allowBluetoothA2DP, .defaultToSpeaker]
|
||||
: [.mixWithOthers, .allowBluetoothA2DP, .defaultToSpeaker]
|
||||
}
|
||||
}
|
||||
+22
-9
@@ -487,7 +487,7 @@ doesn't use, and `SpeechAnalyzer` runs without it in the app and the keyboard al
|
||||
`anoma.ly/hex/privacy`). Each row has a one-line description at most. The pages:
|
||||
- **Dictation:** Style, Lowercase, Format lists, Dictation language, Translate what I say, Clean up
|
||||
what I say, Custom vocabulary (its list below the switch), Keep mic warm,
|
||||
and Always use iPhone microphone.
|
||||
and Microphone.
|
||||
- **Keyboard:** Keyboard, **Full** (the default) or **Dictation bar** (stored
|
||||
as `FullKeyboardSettings.isEnabled`, App Group key `experiments.fullKeyboard`
|
||||
from when the full keyboard was an experiment: unset or true is Full, false
|
||||
@@ -883,14 +883,27 @@ doesn't use, and `SpeechAnalyzer` runs without it in the app and the keyboard al
|
||||
itself, and the keepalive is input only (an `AVAudioEngine` input tap, no
|
||||
output node: its output element is off). A keepalive that keeps stopping by
|
||||
itself is restarted at once, then after 1 s, 2 s, … up to 30 s, not every
|
||||
100 ms. **Always use iPhone
|
||||
microphone** (on by default) records from the built-in microphone, so a car
|
||||
or headphones never drop into call audio; turning it off also allows a
|
||||
Bluetooth HFP microphone (still mixing). In-keyboard dictation records
|
||||
through WebKit, whose capture session (`playAndRecord`, `videoChat`, no
|
||||
`mixWithOthers`) no app can change: other apps' video and music pause while
|
||||
it records and WebKit ends it without telling them, so once it has ended the
|
||||
keyboard activates and deactivates its own session with
|
||||
100 ms. **Microphone** (`MicrophoneChoice`, `MicrophoneRoute`) picks each
|
||||
dictation's input: **Automatic** (the default) a wired or USB headset's
|
||||
microphone, the car's in CarPlay (the driver's microphone Siri uses, where
|
||||
the iPhone's hears the speakers and the road), else the iPhone's, so AirPods
|
||||
and other Bluetooth headphones keep playing at full quality and nothing
|
||||
waits for call audio; **iPhone** always the built-in one; **Bluetooth** also
|
||||
Bluetooth hands-free microphones (AirPods, Bluetooth car kits, which iOS
|
||||
can't tell from headphones), in call audio (8–16 kHz) and still mixing. Only
|
||||
Bluetooth adds `allowBluetoothHFP`, and the input is always set
|
||||
explicitly. The warm keepalive stays on the iPhone's microphone whatever the
|
||||
choice, so a warm session never holds a car or headset in call audio between
|
||||
dictations; a dictation moves to its input as it starts (a Bluetooth
|
||||
headset's call link can take 0.5–2 s, unmeasured here). The setting replaced
|
||||
Always use iPhone microphone: left on it reads as Automatic, turned off as
|
||||
Bluetooth. In-keyboard dictation asks WebKit for the same input by name
|
||||
(`deviceId`), read from the keyboard's own session; left to itself WebKit
|
||||
takes the input of the route already playing, the iPhone's while a car or
|
||||
headphones play over A2DP. Its capture session (`playAndRecord`,
|
||||
`videoChat`, no `mixWithOthers`) no app can change: other apps' video and
|
||||
music pause while it records and WebKit ends it without telling them, so
|
||||
once it has ended the keyboard activates and deactivates its own session with
|
||||
`notifyOthersOnDeactivation` (`InterruptedAudio`), for players that resume
|
||||
on `.shouldResume`. Unverified on an iPhone: the simulator has no audio
|
||||
interruptions.
|
||||
|
||||
Reference in New Issue
Block a user