知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
feat: Interpreting can run hands-free: while Cicada listens to a meeting, just start talking and the translation goes out after a one-second pause
wqugurua44d0e8b8abd
diff --git a/.claude/skills/audio-test/references/speak.md b/.claude/skills/audio-test/references/speak.mdindex a418809..81a1d90 100644--- a/.claude/skills/audio-test/references/speak.md+++ b/.claude/skills/audio-test/references/speak.md@@ -41,8 +41,34 @@ Two rounds right after room rounds had every press at 0.0 s (unit setting changeWhat it found: with the plain mic (`VP=off`) the meeting's English came back from the speakers and Ming interpreted it as me — my sentences 50/27/23 %, the meeting sent back into itself, and a silent press sent the meeting back 3 of 3 times. Through echo cancellation: 86–100 %, none of the meeting. A silent press in a quiet room came back as 嗯 → "Hmm." until PressSpeech and the filler check.+## 不用按键 (hands-free)++`lsctl handsFree:on`; the unit runs the whole time with Apple's advanced ducking at max (`VoiceMic.advancedDucking`), `HandsFreeDetector` cuts sentences, and each goes through the press pipeline. Debug: `handsFreeDump:<path>` writes the echo-cancelled stream as raw 16 kHz float32; the log has `hands-free: voice began / sentence of / only … of voice / … chars, too short / the meeting's own words`.++| Round | What plays | Pass |+|---|---|---|+| Quiet | ESP32 says one sentence, nothing on the speakers | ≥ 90 % |+| Meeting 56 % | meeting from the speakers, ESP32 talks over it | ≥ 70 %, none of the meeting's words |+| Two sentences | the same, 2 s apart | both sent |+| Meeting only, 100 % | nobody talks, 5 rounds | 0 sent |++2026-11-11 (MacBook Pro 14, ESP32 10 cm from the mic, the sentence `我同意这个数字。设计那个岗位很急,周四之前我会回复。`, scored on the `me` lines). Rounds were run before the echo check, the three-unit minimum and listening-only were added, except where marked:++- Quiet: 23/23 ×3.+- Meeting 56 %: 20, 20, 18, 16, 18/23; with the final filters 20, 16, 16. The first word or two is lost: the unit takes the voice away for ~0.5 s before the ducking holds.+- Two sentences 2 s apart: 4 of 4 sent (one only after the round's record had ended: room noise held the sentence open to the 20 s cut).+- Meeting 100 % with the ESP32: nothing detected (too quiet there; the iPhone was louder).+- Meeting only, 100 %: before the echo check 2 of 15 sentences heard were the meeting's own words ("营收增长;四名工程师;下半年"); after it, none in 5 rounds. The check itself hasn't been seen firing on a reproduced leak yet.+- The other sends in those rounds ("妈妈,我饿了。", "云南是不是雨季?", "喂。", "咳咳。") were people in the room: a minute of the idle stream with nothing playing ran at −7 to −15 dB and the on-device recognizer heard Chinese speech in it.++Unit ducking, measured on the stream (share of 200 ms frames of the ESP32's sentence over −45 dB): min 12/27 at 56 %, 3/27 at 100 %; advanced max 23 and 15; plain max 25 and 23, but that ducks the meeting ~25 dB for as long as the unit runs, Cicada's capture too (−65 against −40 dB). Advanced max dips Cicada's capture to −66 dB only while someone speaks near the mic.++To do, in a quiet room: meeting only for 5 minutes at 56 % and 100 %; the rounds above again on the final build with each sentence matched to its START/END; the talk-key rounds with hands-free off and on, and `MIC=on`; `voiced` against sent.+## Open+- **Hands-free hears everyone near the Mac as me**, and each loud stretch costs a Ming call. While it runs the unit's processing is on, so other apps hear the built-in mic muted (#24); it runs only while a meeting is listened to, when the meeting hears the virtual mic. Not measured: a real voice, typing, music.+- **Sounds that aren't speech.** In a quiet room a silent press with typing nearby went out as "The sound of typing on a computer keyboard." (Ming described the sound). The on-device recognizer can't vote it down: it heard 0 characters of a real sentence too.- **Voice output stalls.** Now and then a sentence's voice to BlackHole stops until the next one's stall check rebuilds the output (`voice output stalled … rebuilt`): seen with echo cancellation on and off, once a sentence going out 8 s late. Count `voiced` against `sent`.- **The ports** have no echo cancellation on the talk key: Windows (b155b46) and Linux drop a press the computer played through for more than half, so talking over the other side isn't sent there. Their silent-press and filler checks are unit-tested and, on Windows, checked in the VM with `cicadactl speak silence.wav` / `me-zh.wav`; real echo needs a real PC.diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.stringsindex 36c99c7..8f7131b 100644--- a/Resources/en.lproj/Localizable.strings+++ b/Resources/en.lproj/Localizable.strings@@ -808,6 +808,10 @@"把我说的翻译给对方" = "Translate what I say for them";"说话" = "Speaking";"按住说话" = "Hold to talk";+"不用按键" = "Hands-free";+"打开麦克风时暂停" = "Paused while the mic is on";+"开始听会议后生效" = "Starts when you start listening";+"开口就翻译,停顿 1 秒后说出去" = "Translates as you speak, sent after a 1-second pause";"说%@,对方听到" = "You speak %@, they hear";"按键还需要“输入监控”权限" = "The key needs Input Monitoring";"系统麦克风还是 %@,别的软件听不到你" = "System mic is still %@; other apps can't hear you";diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.stringsindex 6272a8a..420c871 100644--- a/Resources/ja.lproj/Localizable.strings+++ b/Resources/ja.lproj/Localizable.strings@@ -808,6 +808,10 @@"把我说的翻译给对方" = "自分の発言を相手に翻訳して伝える";"说话" = "話す";"按住说话" = "押して話す";+"不用按键" = "キーを押さずに";+"打开麦克风时暂停" = "マイクをオンにしている間は一時停止";+"开始听会议后生效" = "会議を聞き始めると有効になります";+"开口就翻译,停顿 1 秒后说出去" = "話すとすぐ翻訳、1 秒止まると相手に届きます";"说%@,对方听到" = "%@で話すと、相手には";"按键还需要“输入监控”权限" = "キーには「入力監視」の許可が必要";"系统麦克风还是 %@,别的软件听不到你" = "システムのマイクがまだ %@ のため、ほかのアプリに声が届きません";diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.stringsindex e4070e2..0b5a8a5 100644--- a/Resources/ko.lproj/Localizable.strings+++ b/Resources/ko.lproj/Localizable.strings@@ -808,6 +808,10 @@"把我说的翻译给对方" = "내 말을 상대에게 번역";"说话" = "말하기";"按住说话" = "누르고 말하기";+"不用按键" = "키 없이 말하기";+"打开麦克风时暂停" = "마이크를 켜는 동안 일시 중지";+"开始听会议后生效" = "회의 듣기를 시작하면 켜집니다";+"开口就翻译,停顿 1 秒后说出去" = "말하면 바로 번역, 1초 멈추면 상대에게 전달";"说%@,对方听到" = "%@로 말하면 상대에게";"按键还需要“输入监控”权限" = "키에 ‘입력 모니터링’ 권한이 필요";"系统麦克风还是 %@,别的软件听不到你" = "시스템 마이크가 아직 %@(이)라 다른 앱이 듣지 못합니다";diff --git a/Resources/zh-Hans.lproj/Localizable.strings b/Resources/zh-Hans.lproj/Localizable.stringsindex b22f64e..78d5eeb 100644--- a/Resources/zh-Hans.lproj/Localizable.strings+++ b/Resources/zh-Hans.lproj/Localizable.strings@@ -793,6 +793,10 @@"把我说的翻译给对方" = "把我说的翻译给对方";"说话" = "说话";"按住说话" = "按住说话";+"不用按键" = "不用按键";+"打开麦克风时暂停" = "打开麦克风时暂停";+"开始听会议后生效" = "开始听会议后生效";+"开口就翻译,停顿 1 秒后说出去" = "开口就翻译,停顿 1 秒后说出去";"说%@,对方听到" = "说%@,对方听到";"按键还需要“输入监控”权限" = "按键还需要“输入监控”权限";"系统麦克风还是 %@,别的软件听不到你" = "系统麦克风还是 %@,别的软件听不到你";diff --git a/Sources/Cicada/AppModel.swift b/Sources/Cicada/AppModel.swiftindex dd334ac..a728d10 100644--- a/Sources/Cicada/AppModel.swift+++ b/Sources/Cicada/AppModel.swift@@ -33,6 +33,9 @@ final class AppModel: ObservableObject {var roomEchoGate = true/// The Mac's lines of late (wall clock), and room lines waiting to be told apart from their echo.private var recentOnline: [EchoMatch.Heard] = []+ /// The meeting's last 30 s, its lines and their translations, for 不用按键 to tell its echo.+ private var recentMeeting: [EchoMatch.Heard] = []+ private var recentMeetingSegs: [Int: (start: Double, end: Double)] = [:]private(set) var heldRoom: [(id: Int, seg: Segment, duration: Double, heard: EchoMatch.Heard)] = []/// What each engine shows as the line in progress, and when it last changed.private var liveMain = (src: "", dst: "", at: Date.distantPast)@@ -169,6 +172,7 @@ final class AppModel: ObservableObject {/// The last speaker edit, offered as 撤销 at the bottom of both windows for a few seconds.@Published var speakerUndo: SpeakerUndo?private var speakerSetting: AnyCancellable?+ private var handsFreeSetting: AnyCancellable?var openOnboarding: (() -> Void)?var openMainWindow: (() -> Void)?@@ -231,6 +235,20 @@ final class AppModel: ObservableObject {self.store.setVoice(lineID: line, voice)if let id = self.store.liveID { self.speakerNamer.guess(id) }}+ // 不用按键 runs only while a meeting is being listened to: its lines are what tells the meeting's+ // echo (`meetingSaid`), and the running unit mutes the built-in mic for other apps (#24), which+ // then hear the virtual mic anyway. It pauses while 打开麦克风 is on: the room shares the unit and+ // is heard unprocessed, and everyone at the table would be interpreted as me.+ handsFreeSetting = Publishers.CombineLatest4(settings.$speakHandsFree, settings.$listenSource, settings.$speakEnabled, $running)+ .sink { [weak self] on, _, _, _ in+ DispatchQueue.main.async {+ MainActor.assumeIsolated {+ guard let self else { return }+ self.speak.handsFree = on && self.settings.speakEnabled && !self.settings.hearsRoom && self.running+ self.speak.refreshHandsFree()+ }+ }+ }speakerSetting = settings.$speakerVoices.sink { [weak self] on inTranscriptExport.voices = onself?.listen.router.setVoiceCapture(on)@@ -348,6 +366,15 @@ final class AppModel: ObservableObject {self.overlay.setSpeaking(.init(phase: phase, source: src, translation: dst))}}+ speak.meetingSaid = { [weak self] text, from, to in+ let heard = EchoMatch.Heard(text: text, start: from.timeIntervalSinceReferenceDate, end: to.timeIntervalSinceReferenceDate)+ guard let self else { return false }+ if EchoMatch.isEcho(heard, online: self.recentMeeting) { return true }+ // The meeting was playing: its line (and translation) may land a moment after Ming's answer.+ guard self.listen.router.stats().silenceRun < EchoMatch.window else { return false }+ try? await Task.sleep(nanoseconds: UInt64(EchoMatch.hold * 1_000_000_000))+ return EchoMatch.isEcho(heard, online: self.recentMeeting)+ }speak.onUtterance = { [weak self] src, dst, from, to, ago inself?.recordSaid(src, dst, from: from, to: to, secondsAgo: ago)}@@ -1408,6 +1435,11 @@ final class AppModel: ObservableObject {/// A sentence from the Mac's audio: recorded, and remembered to tell the room's copy of it.private func heardOnline(_ seg: Segment, duration: Double) {+ let at = CFAbsoluteTimeGetCurrent()+ recentMeeting.append(.init(text: seg.text, start: at - duration, end: at))+ recentMeeting.removeAll { $0.end < at - 30 }+ recentMeetingSegs[seg.id] = (at - duration, at)+ recentMeetingSegs = recentMeetingSegs.filter { $0.value.end >= at - 30 }if roomListen.isRunning {let now = CFAbsoluteTimeGetCurrent()recentOnline.append(.init(text: seg.text, start: now - duration, end: now))@@ -1459,6 +1491,7 @@ final class AppModel: ObservableObject {}private func translated(_ segID: Int, _ text: String) {+ if let t = recentMeetingSegs[segID] { recentMeeting.append(.init(text: text, start: t.start, end: t.end)) }if heldJoin?.seg.id == segID { heldJoin?.translation = text }if let i = heldRoom.firstIndex(where: { $0.id == segID }) { heldRoom[i].seg.translation = text }guard let line = lineForSegment[segID], !refinedLines.contains(line) else { return }@@ -2210,6 +2243,9 @@ final class AppModel: ObservableObject {case "speakOut": speak.debugOutputURL = arg.isEmpty ? nil : URL(fileURLWithPath: arg)case "speakFile": speak.speakFile(URL(fileURLWithPath: arg))// talkDown / talkUp: the talk key held and let go, with the real microphone (audio tests).+ // handsFree:on|off: 不用按键, as the setting.+ case "handsFree": settings.speakHandsFree = arg != "off"+ case "handsFreeDump": speak.setHandsFreeDump(arg.isEmpty ? nil : arg)case "talkDown": speak.pressBegan()case "talkUp": speak.pressEnded()// stall:<seconds> blocks the main thread, to check the watchdog samples it.diff --git a/Sources/Cicada/DebugControl.swift b/Sources/Cicada/DebugControl.swiftindex c63660c..2f3cf52 100644--- a/Sources/Cicada/DebugControl.swift+++ b/Sources/Cicada/DebugControl.swift@@ -119,6 +119,7 @@ extension AppModel {all["speak"] = { ["enabled": self.settings.speakEnabled, "phase": "\(self.speakPhase)", "mic": self.speak.micDeviceName,"output": self.speak.outputDevice()?.name ?? "", "voiceMicInUse": self.voiceMic.inUse,+ "handsFree": self.speak.handsFree,"test": ["shown": self.speakTestShown, "phase": "\(self.speakTester.phase)"] as [String: Any],] }all["ai"] = { [diff --git a/Sources/Cicada/HandsFree.swift b/Sources/Cicada/HandsFree.swiftnew file mode 100644index 0000000..f5f838a--- /dev/null+++ b/Sources/Cicada/HandsFree.swift@@ -0,0 +1,92 @@+import Foundation++/// 不用按键 (hands-free interpreting): the mic through echo cancellation all the time, a sentence from+/// when your voice rises over the room's floor to `hangover` of quiet after it. Fed the echo-cancelled+/// mic block by block (`VoiceMic`, ~10 ms). A blip (a click, a cough of the speakers) is not a start+/// until it has lasted `onset`; a pause between words shorter than `hangover` doesn't end the sentence.+struct HandsFreeDetector {+ struct Tuning: Equatable {+ /// Seconds of voice before a sentence starts (gaps under `bridge` don't reset it).+ var onset = 0.1+ var bridge = 0.15+ /// Quiet that ends a sentence.+ var hangover = 1.0+ /// A sentence is cut here (Ming takes a sentence or two; the next one starts at once).+ var longest = 20.0+ /// The voice must be this many times the room's floor, and at least `lowest`.+ var margin: Float = 4+ var lowest: Float = 0.004+ /// Once talking, voice goes on down to this share of the line (a word's quiet ending isn't quiet).+ var hold: Float = 0.5+ static let standard = Tuning()+ }++ /// `ended(cut: true)`: `longest` reached while still talking; the next sentence has begun.+ enum Event: Equatable { case none, began, ended(cut: Bool) }++ var tuning: Tuning+ private(set) var talking = false+ private(set) var length = 0.0+ private var voiced = 0.0+ private var gap = 0.0+ private var quiet = 0.0+ /// The quietest block of each of the last seconds: the room's floor.+ private var quietest: [Float] = []+ private var second: Float = .infinity+ private var elapsed = 0.0++ init(tuning: Tuning = .standard) { self.tuning = tuning }++ var floor: Float { quietest.count < 3 ? tuning.lowest / tuning.margin : quietest.sorted()[quietest.count / 5] }+ var line: Float { max(tuning.lowest, floor * tuning.margin) }++ mutating func reset() {+ talking = false+ length = 0; voiced = 0; gap = 0; quiet = 0+ }++ /// Seconds of floor learned: nothing starts before 3 (the unit's first moments are a burst, and a+ /// noisy room would read as a voice until its floor is known).+ var ready: Bool { quietest.count >= 3 }++ mutating func feed(rms: Float, seconds: Double) -> Event {+ // Always learning: speech has a gap in every second, so a sentence doesn't raise the floor, and a+ // room that got noisier (a fan on) can't leave it "talking" for good.+ learn(rms, seconds)+ guard ready else { return .none }+ if !talking {+ if rms >= line {+ voiced += seconds; gap = 0+ } else {+ gap += seconds+ if gap > tuning.bridge { voiced = 0 }+ }+ guard voiced >= tuning.onset else { return .none }+ talking = true+ length = voiced; quiet = 0; voiced = 0; gap = 0+ return .began+ }+ length += seconds+ quiet = rms >= line * tuning.hold ? 0 : quiet + seconds+ if quiet >= tuning.hangover {+ reset()+ return .ended(cut: false)+ }+ // Still talking: this sentence goes now and the next one starts here.+ if length >= tuning.longest {+ length = 0+ return .ended(cut: true)+ }+ return .none+ }++ private mutating func learn(_ rms: Float, _ seconds: Double) {+ second = min(second, rms)+ elapsed += seconds+ guard elapsed >= 1 - 1e-9 else { return }+ quietest.append(second)+ if quietest.count > 10 { quietest.removeFirst() }+ second = .infinity+ elapsed = 0+ }+}diff --git a/Sources/Cicada/Settings.swift b/Sources/Cicada/Settings.swiftindex cd1d63b..018123a 100644--- a/Sources/Cicada/Settings.swift+++ b/Sources/Cicada/Settings.swift@@ -35,6 +35,11 @@ final class AppSettings: ObservableObject {@Published var speakConfirmed: Bool {didSet { save() }}+ /// 不用按键: interpret whenever I speak, no key held (`HandsFreeDetector`). Mac only: the ports+ /// have no echo cancellation to hear me over the meeting.+ @Published var speakHandsFree: Bool {+ didSet { save() }+ }/// Locale of the language I speak.@Published var speakFrom: String {didSet { save() }@@ -264,6 +269,7 @@ final class AppSettings: ObservableObject {speakConfirmed = defaults.object(forKey: "speakConfirmed") as? Bool ?? defaults.bool(forKey: "speakEnabled")speakFrom = defaults.string(forKey: "speakFrom")?? speakLocale(forLanguage: Cicada.myLanguage(systemLanguages: Locale.preferredLanguages))+ speakHandsFree = defaults.bool(forKey: "speakHandsFree")speakTo = defaults.string(forKey: "speakTo") ?? "room"speakOutput = defaults.string(forKey: "speakOutput") ?? ""autoSystemMic = defaults.object(forKey: "autoSystemMic") as? Bool ?? true@@ -323,6 +329,7 @@ final class AppSettings: ObservableObject {defaults.set(speakEnabled, forKey: "speakEnabled")defaults.set(speakConfirmed, forKey: "speakConfirmed")defaults.set(speakFrom, forKey: "speakFrom")+ defaults.set(speakHandsFree, forKey: "speakHandsFree")defaults.set(speakTo, forKey: "speakTo")defaults.set(speakOutput, forKey: "speakOutput")defaults.set(autoSystemMic, forKey: "autoSystemMic")diff --git a/Sources/Cicada/SettingsWindow.swift b/Sources/Cicada/SettingsWindow.swiftindex 6d18ddf..abd33f2 100644--- a/Sources/Cicada/SettingsWindow.swift+++ b/Sources/Cicada/SettingsWindow.swift@@ -505,6 +505,13 @@ struct SettingsView: View {}group(L("说话")) {SettingsRow(title: L("按住说话")) { ShortcutField(model: model, role: .talk) }+ // Hands-free runs only while listening, and pauses with the room mic on (`AppModel.handsFreeSetting`).+ SettingsRow(title: L("不用按键"),+ detail: !settings.speakHandsFree ? L("开口就翻译,停顿 1 秒后说出去")+ : settings.hearsRoom ? L("打开麦克风时暂停") : model.running ? L("开口就翻译,停顿 1 秒后说出去") : L("开始听会议后生效")) {+ Toggle("不用按键", isOn: $settings.speakHandsFree)+ .toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)+ }SettingsRow(title: L("说\(settings.speakFromLang.name),对方听到")) {PillMenu(value: settings.speakTo == "room" ? L("跟随对方(\(targetName(model.speak.targetCode)))") : targetName(settings.speakTo),options: [("room", L("跟随对方"))] + targetLanguages.map { ($0.code, $0.name) }) {diff --git a/Sources/Cicada/SpeakEngine.swift b/Sources/Cicada/SpeakEngine.swiftindex 426b545..154eccc 100644--- a/Sources/Cicada/SpeakEngine.swift+++ b/Sources/Cicada/SpeakEngine.swift@@ -103,11 +103,17 @@ final class SpeakEngine {let settings: AppSettingsprivate(set) var phase: Phase = .idle {- // The press's echo-cancelling unit is kept until its sentence has gone out, not let go of- // at key-up: a press while that sentence still plays reuses it instead of remaking the- // voice output under it. Idle, it would silence the mic for every other app (the room's- // own use keeps it).- didSet { if phase == .idle, !voiceMic.inUse { voiceMic.release() } }+ didSet {+ // The press's echo-cancelling unit is kept until its sentence has gone out, not let go of+ // at key-up: a press while that sentence still plays reuses it instead of remaking the+ // voice output under it. Idle, it would silence the mic for every other app (the room's+ // and hands-free's own use keeps it).+ if phase == .idle, !voiceMic.inUse { voiceMic.release() }+ // Hands-free: a sentence said while the last one was translated waits its turn.+ if handsFree, phase == .idle || phase == .speaking, !segments.isEmpty {+ DispatchQueue.main.async { [weak self] in MainActor.assumeIsolated { self?.nextSegment() } }+ }+ }}private var mic = AVAudioEngine()@@ -171,6 +177,167 @@ final class SpeakEngine {wireOutput()}+ // MARK: Hands-free++ /// 不用按键: the mic through echo cancellation the whole time, and every sentence I say is+ /// interpreted as a press would be (`HandsFreeDetector` says where it starts and ends). Set by the+ /// app: on with the setting, off while 打开麦克风 hears the room (that unit is shared, and the+ /// room is heard unprocessed). The talk key still works and pauses the detector while held.+ var handsFree = false {+ didSet { if handsFree != oldValue { refreshHandsFree() } }+ }+ /// A hands-free sentence with less voice than this is not sent: every real sentence had ≥ 1.95 s,+ /// what Ming made a sentence of out of the meeting's leftovers ("啊!我要吓死你了!") 0.48 s.+ static let handsFreeVoiced = 0.8+ /// The press being finished is a hands-free sentence.+ private var pressHandsFree = false+ /// Whether a hands-free sentence is mostly what the meeting said around it (its lines or their+ /// translations, `EchoMatch`): the meeting's leftovers through the unit, made into a sentence by+ /// Ming ("营收增长;四名工程师;下半年" with the meeting at 100 % and nobody talking).+ var meetingSaid: ((_ text: String, _ from: Date, _ to: Date) async -> Bool)?+ private var handsFreeInput: AudioObjectID?+ private var handsFreeTimer: Timer?+ /// Sentences heard, waiting for the one before them to be translated.+ private var segments: [(buffers: [AVAudioPCMBuffer], start: Date, end: Date)] = []+ /// Only touched on `micQueue`.+ private nonisolated(unsafe) var detector = HandsFreeDetector()+ private nonisolated(unsafe) var recent: [AVAudioPCMBuffer] = []+ private nonisolated(unsafe) var recentSeconds = 0.0+ private nonisolated(unsafe) var segment: [AVAudioPCMBuffer]?+ private nonisolated(unsafe) var segmentStart = Date()+ /// Debug (`handsFreeDump:<path>`): the echo-cancelled mic as raw 16 kHz float32, to tune the detector.+ private nonisolated(unsafe) var dump: FileHandle?+ func setHandsFreeDump(_ path: String?) {+ micQueue.sync {+ try? dump?.close()+ dump = nil+ guard let path else { return }+ FileManager.default.createFile(atPath: path, contents: nil)+ dump = FileHandle(forWritingAtPath: path)+ }+ }+ /// Audio kept from before the detector is sure: its onset and the first syllable's rise.+ private nonisolated static let lookback = 0.8++ /// Attaches or lets go of the mic to match `handsFree`, the setting and the devices; checked again+ /// every 2 s while on (the unit is made for one output: headphones plugged in need a new one).+ func refreshHandsFree() {+ let want = handsFree && settings.speakEnabled && echoCancel && analyzerFormat != nil ? echoInput : nil+ if let d = handsFreeInput, want != d || !voiceMic.serves("handsfree", input: d) { stopHandsFree() }+ if handsFree, handsFreeTimer == nil {+ handsFreeTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] _ in+ MainActor.assumeIsolated { self?.refreshHandsFree() }+ }+ } else if !handsFree {+ handsFreeTimer?.invalidate()+ handsFreeTimer = nil+ }+ guard let d = want, handsFreeInput == nil else { return }+ handsFreeInput = d+ voiceMic.advancedDucking = true+ voiceMic.prepare(input: d) { [weak self] ok in+ DispatchQueue.main.async {+ MainActor.assumeIsolated {+ guard let self else { return }+ // Stopped while it was being made: nobody else may be left to give it back.+ guard self.handsFreeInput == d else {+ if self.phase == .idle, !self.voiceMic.inUse { self.voiceMic.release() }+ return+ }+ let queue = self.micQueue+ let attached = ok && self.voiceMic.attach("handsfree", input: d) { [weak self] buf in+ queue.async { self?.hear(buf) }+ }+ if !attached { self.handsFreeInput = nil }+ debugLog("hands-free: \(attached ? "listening" : "mic not ready, trying again")")+ }+ }+ }+ }++ private func stopHandsFree() {+ guard handsFreeInput != nil else { return }+ handsFreeInput = nil+ voiceMic.detach("handsfree")+ micQueue.sync { detector.reset(); segment = nil; recent = []; recentSeconds = 0 }+ // The talk key's unit keeps the meeting at its level again (made anew once nobody uses it).+ voiceMic.advancedDucking = false+ // Not kept for the next press: while it exists every other app's mic hears almost nothing (#24).+ if phase == .idle, !voiceMic.inUse { voiceMic.release() }+ debugLog("hands-free: stopped")+ }++ /// On `micQueue`: one block of the echo-cancelled mic.+ private nonisolated func hear(_ buf: AVAudioPCMBuffer) {+ let n = Int(buf.frameLength)+ guard n > 0, let d = buf.floatChannelData?[0] else { return }+ let seconds = Double(n) / buf.format.sampleRate+ dump?.write(Data(bytes: d, count: n * 4))+ // The talk key held: that press has the mic.+ if feeding {+ segment = nil+ detector.reset()+ return+ }+ recent.append(buf)+ recentSeconds += seconds+ while recentSeconds - Double(recent[0].frameLength) / buf.format.sampleRate >= Self.lookback {+ recentSeconds -= Double(recent.removeFirst().frameLength) / buf.format.sampleRate+ }+ var sum: Float = 0+ for i in 0..<n { sum += d[i] * d[i] }+ let rms = (sum / Float(n)).squareRoot()+ let line = detector.line+ switch detector.feed(rms: rms, seconds: seconds) {+ case .began:+ segment = recent+ segmentStart = Date().addingTimeInterval(-recentSeconds)+ debugLog(String(format: "hands-free: voice began (%.0f dB over a %.0f dB line)", 20 * log10(max(rms, 1e-6)), 20 * log10(line)))+ DispatchQueue.main.async { [weak self] in MainActor.assumeIsolated { self?.voiceBegan() } }+ case .ended(let cut):+ guard let s = segment else { return }+ let start = segmentStart+ segment = cut ? [] : nil+ segmentStart = Date()+ DispatchQueue.main.async { [weak self] in MainActor.assumeIsolated { self?.voiceEnded(s, start: start, cut: cut) } }+ case .none:+ segment?.append(buf)+ }+ }++ private func voiceBegan() {+ if phase == .idle { onLive?(.listening, "", "") }+ }++ private func voiceEnded(_ buffers: [AVAudioPCMBuffer], start: Date, cut: Bool) {+ debugLog(String(format: "hands-free: sentence of %.1f s%@", Date().timeIntervalSince(start), cut ? " (cut, still talking)" : ""))+ segments.append((buffers, start, Date()))+ nextSegment()+ }++ /// Sends the oldest sentence heard on as a press would be, once the one before it is translated.+ private func nextSegment() {+ guard phase == .idle || phase == .speaking, !segments.isEmpty else { return }+ guard let format = analyzerFormat, let input = beginUtterance() else {+ debugLog("hands-free: transcriber not ready, sentence dropped")+ segments.removeFirst()+ return+ }+ let s = segments.removeFirst()+ pressStarted = s.start+ pressPlain = false+ pressHandsFree = true+ phase = .listening+ let conv = PCMConverter()+ for buf in s.buffers {+ guard let c = conv.convert(buf, to: format) else { continue }+ input.append(c)+ micQueue.sync { keepForMing(c) }+ }+ releasedAt = s.end+ finishUtterance()+ }+private func wireOutput() {out.attach(player)// Pointing the output at a device (the first sentence, BlackHole installed, headphones@@ -303,6 +470,7 @@ final class SpeakEngine {}debugLog("speak: press began")pressStarted = Date()+ pressHandsFree = falsephase = .listeningonLive?(.listening, "", "")startMic(format: format, input: input)@@ -357,6 +525,7 @@ final class SpeakEngine {return false}pressStarted = Date()+ pressHandsFree = falsephase = .listeningonLive?(.listening, "", "")let conv = PCMConverter()@@ -459,7 +628,7 @@ final class SpeakEngine {/// The press as a WAV file in memory (44-byte RIFF header + little-endian samples), and whether/// anyone spoke in it (`PressSpeech`).- private func takePressWAV() -> (wav: Data?, spoken: Bool) {+ private func takePressWAV() -> (wav: Data?, spoken: Bool, voiced: Double) {let samples = micQueue.sync { () -> [Int16] indefer { pressSamples = [] }return pressSamples@@ -467,7 +636,7 @@ final class SpeakEngine {let measure = PressSpeech.measure(samples)let spoken = measure.spokendebugLog("speak: press of \(String(format: "%.1f", Double(samples.count) / 16_000)) s, \(measure.summary)")- guard samples.count >= 16_000 / 4 else { return (nil, spoken) }+ guard samples.count >= 16_000 / 4 else { return (nil, spoken, measure.voiced) }var d = Data()func u32(_ v: UInt32) { withUnsafeBytes(of: v.littleEndian) { d.append(contentsOf: $0) } }func u16(_ v: UInt16) { withUnsafeBytes(of: v.littleEndian) { d.append(contentsOf: $0) } }@@ -478,7 +647,7 @@ final class SpeakEngine {samples.withUnsafeBufferPointer { buf infor s in buf { withUnsafeBytes(of: s.littleEndian) { d.append(contentsOf: $0) } }}- return (d, spoken)+ return (d, spoken, measure.voiced)}private nonisolated func recordMic(_ buffer: AVAudioPCMBuffer) {@@ -506,12 +675,22 @@ final class SpeakEngine {Task { await u.input.finish() }let released = releasedAt ?? Date()releasedAt = nil- let (wav, spoken) = takePressWAV()+ let (wav, spoken, voiced) = takePressWAV()probe?.released = released// A press too quiet for PressSpeech: nobody spoke (Ming would hear 嗯 in the room's hush and// the meeting "Hmm."), or a voice from across the desk under a line the meeting's leftover// echo raised. The on-device recognizer decides which once it has finished.let quiet = wav != nil && !spoken && probe == nil+ // Hands-free: a blip or the meeting's leftovers, not a sentence (Ming would make one up).+ if pressHandsFree, voiced < Self.handsFreeVoiced {+ debugLog(String(format: "hands-free: only %.2f s of voice, nothing sent", voiced))+ Task { _ = await u.text.value }+ finals = []+ volatile = ""+ phase = .idle+ onLive?(.idle, "", "")+ return+ }// The meeting playing through most of a press on the plain mic: don't send its echo back.if pressPlain, probe == nil, let share = playedShare?(pressStarted, released), share > Self.echoShare {debugLog(String(format: "speak: the Mac played through %.0f%% of the press (echo), nothing sent", share * 100))@@ -560,6 +739,17 @@ final class SpeakEngine {let heard = await (early ?? startMing()).valuedebugLog("speak: on-device heard \(text.count) chars, Ming \(heard.map { "\($0.original.count)" } ?? "-") chars")if let heard { text = heard.original }+ // Hands-free: a word or two is a noise Ming named (喂, 咳咳; the talk key is there for 好的),+ // and the meeting's own words are its echo.+ let short = EchoMatch.units(text).count < 3+ var echo = false+ if pressHandsFree, !text.isEmpty, !short { echo = await meetingSaid?(text, pressStarted, released) == true }+ if pressHandsFree, !text.isEmpty, short || echo {+ debugLog("hands-free: \(text.count) chars, \(short ? "too short" : "the meeting's own words"): nothing sent")+ phase = .idle+ onLive?(.idle, "", "")+ return+ }// Ming answers recognition and translation together: its whole call counts as `recognize`.let textAt = Date()probe?.text = textdiff --git a/Sources/Cicada/VoiceMic.swift b/Sources/Cicada/VoiceMic.swiftindex 17ab116..ea861cd 100644--- a/Sources/Cicada/VoiceMic.swift+++ b/Sources/Cicada/VoiceMic.swift@@ -18,8 +18,17 @@ import CoreAudio/// the talk key's first words wait for it) and let go of as soon as nobody needs it; the plain mic/// in this process is starved by it the same way. The room holds it for the whole meeting./// AGC is off (it lifts the room's noise with the voice, which recognition likes less), and other-/// audio's ducking is set to its minimum: the meeting must stay audible while you talk.+/// audio's ducking is set to its minimum: the meeting must stay audible while you talk. Hands-free+/// (`advancedDucking`) asks for Apple's advanced ducking instead: the meeting drops while you speak.final class VoiceMic: @unchecked Sendable {+ /// Hands-free: other audio ducked while the unit hears speech (Apple's advanced ducking at its+ /// most), for the units made from now on; a ready unit made the other way is made again when+ /// nobody uses it. Measured with an ESP32 10 cm from the mic as me and the meeting on the MacBook's+ /// speakers, 200 ms stretches of my sentence that came through the unit: at 56 % 12 of 27 with+ /// minimum ducking, 23 with this; at 100 % 3 and 15. Plain maximum ducking (26–25) ducks the+ /// meeting by ~25 dB for as long as the unit runs, Cicada's own capture of it too; this one only+ /// while I speak (the capture dips with it then, and is back to its level when I stop).+ var advancedDucking = falsestatic let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16000, channels: 1, interleaved: false)!private let queue = DispatchQueue(label: "com.wquguru.cicada.voicemic")@@ -27,7 +36,7 @@ final class VoiceMic: @unchecked Sendable {private enum UnitState {case none/// Made for these devices: another mic or output means making it again.- case ready(AudioUnit, input: AudioObjectID, output: AudioObjectID)+ case ready(AudioUnit, input: AudioObjectID, output: AudioObjectID, advanced: Bool)/// Failed to start: given back once nobody uses it.case stale(AudioUnit)}@@ -35,7 +44,7 @@ final class VoiceMic: @unchecked Sendable {private var unit: AudioUnit? {switch state {case .none: nil- case .ready(let u, _, _), .stale(let u): u+ case .ready(let u, _, _, _), .stale(let u): u}}private var building = false@@ -66,13 +75,24 @@ final class VoiceMic: @unchecked Sendable {/// Whether anyone is attached (then nobody may use the plain mic, which the unit starves).var inUse: Bool { lock.withLock { !consumers.isEmpty } }+ /// Whether `key` is attached to a unit made for `input` and the current output (headphones plugged+ /// in or AirPods taking the output leave it on a unit for the old one).+ func serves(_ key: String, input: AudioObjectID) -> Bool {+ let output = SystemAudioTap.defaultOutputDevice()+ return lock.withLock {+ guard consumers[key] != nil, case .ready(_, let i, let o, let a) = state else { return false }+ return i == input && o == output && a == advancedDucking+ }+ }+/// Makes the unit for `input` and the current output in the background, unless it already is;/// `then` hears whether it is ready (at once when it already was).func prepare(input: AudioObjectID, then: ((Bool) -> Void)? = nil) {guard let output = SystemAudioTap.defaultOutputDevice() else { then?(false); return }lock.lock()var ready = false- if case .ready(_, let i, let o) = state { ready = (i, o) == (input, output) }+ let advanced = advancedDucking+ if case .ready(_, let i, let o, let a) = state { ready = (i, o, a) == (input, output, advanced) }if ready { lock.unlock(); then?(true); return }if let then { waiting.append(then) }if building { lock.unlock(); return }@@ -80,11 +100,11 @@ final class VoiceMic: @unchecked Sendable {lock.unlock()queue.async { [self] inlet t0 = Date()- let made = make(input: input, output: output)+ let made = make(input: input, output: output, advanced: advanced)let (ok, told) = lock.withLock { () -> (Bool, [(Bool) -> Void]) inif let old = unit, consumers.isEmpty { AudioComponentInstanceDispose(old); state = .none }var ok = false- if let made, unit == nil { state = .ready(made, input: input, output: output); bypassed = nil; ok = true } else if let made { AudioComponentInstanceDispose(made) }+ if let made, unit == nil { state = .ready(made, input: input, output: output, advanced: advanced); bypassed = nil; ok = true } else if let made { AudioComponentInstanceDispose(made) }building = falsedefer { waiting = [] }return (ok, waiting)@@ -102,7 +122,7 @@ final class VoiceMic: @unchecked Sendable {func attach(_ key: String, input: AudioObjectID, processing: Bool = true, onAudio: @escaping (AVAudioPCMBuffer) -> Void) -> Bool {guard let output = SystemAudioTap.defaultOutputDevice() else { return false }lock.lock()- guard case .ready(let unit, let i, let o) = state, (i, o) == (input, output) else { lock.unlock(); return false }+ guard case .ready(let unit, let i, let o, _) = state, (i, o) == (input, output) else { lock.unlock(); return false }let first = consumers.isEmptyconsumers[key] = onAudioif processing { processed.insert(key) } else { processed.remove(key) }@@ -175,7 +195,7 @@ final class VoiceMic: @unchecked Sendable {}}- private func make(input: AudioObjectID, output: AudioObjectID) -> AudioUnit? {+ private func make(input: AudioObjectID, output: AudioObjectID, advanced: Bool) -> AudioUnit? {var desc = AudioComponentDescription(componentType: kAudioUnitType_Output, componentSubType: kAudioUnitSubType_VoiceProcessingIO,componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0)guard let comp = AudioComponentFindNext(nil, &desc) else { return nil }@@ -193,7 +213,7 @@ final class VoiceMic: @unchecked Sendable {&& set(kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, output)_ = set(kAUVoiceIOProperty_VoiceProcessingEnableAGC, kAudioUnitScope_Global, 0, UInt32(0))_ = set(kAUVoiceIOProperty_OtherAudioDuckingConfiguration, kAudioUnitScope_Global, 0,- AUVoiceIOOtherAudioDuckingConfiguration(mEnableAdvancedDucking: false, mDuckingLevel: .min))+ AUVoiceIOOtherAudioDuckingConfiguration(mEnableAdvancedDucking: DarwinBoolean(advanced), mDuckingLevel: advanced ? .max : .min))let asbd = Self.format.streamDescription.pointeeok = ok && set(kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, asbd)&& set(kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, asbd)diff --git a/Tests/CicadaTests/HandsFreeTests.swift b/Tests/CicadaTests/HandsFreeTests.swiftnew file mode 100644index 0000000..0504b69--- /dev/null+++ b/Tests/CicadaTests/HandsFreeTests.swift@@ -0,0 +1,101 @@+import Foundation+import Testing+@testable import Cicada++@Suite struct HandsFreeTests {+ private static let block = 170.0 / 16000++ /// Feeds `seconds` of blocks at `rms`; returns the events with the time each came at.+ private func feed(_ d: inout HandsFreeDetector, _ rms: Float, _ seconds: Double, clock: inout Double) -> [(HandsFreeDetector.Event, Double)] {+ var out: [(HandsFreeDetector.Event, Double)] = []+ for _ in 0..<Int((seconds / Self.block).rounded()) {+ let e = d.feed(rms: rms, seconds: Self.block)+ clock += Self.block+ if e != .none { out.append((e, clock)) }+ }+ return out+ }++ @Test func aSentenceStartsAndEndsAfterTheHangover() {+ var d = HandsFreeDetector(), t = 0.0+ #expect(feed(&d, 0.0005, 3, clock: &t).isEmpty)+ let began = feed(&d, 0.05, 2, clock: &t)+ #expect(began.count == 1 && began[0].0 == .began)+ #expect(began[0].1 - 3 < 0.15)+ let ended = feed(&d, 0.0005, 1.5, clock: &t)+ #expect(ended.count == 1 && ended[0].0 == .ended(cut: false))+ #expect(abs(ended[0].1 - 6) < 0.05)+ }++ @Test func nothingStartsBeforeTheFloorIsKnown() {+ var d = HandsFreeDetector(), t = 0.0+ #expect(feed(&d, 0.05, 1, clock: &t).isEmpty)+ }++ /// The room got noisier while quiet: the floor follows, the noise doesn't hold a sentence open.+ @Test func aRoomThatGetsNoisierEndsTheSentence() {+ var d = HandsFreeDetector(), t = 0.0+ _ = feed(&d, 0.0005, 3, clock: &t)+ let events = feed(&d, 0.008, 15, clock: &t).map(\.0)+ #expect(events.first == .began)+ #expect(events.last == .ended(cut: false))+ #expect(!d.talking)+ }++ @Test func aClickIsNotASentence() {+ var d = HandsFreeDetector(), t = 0.0+ _ = feed(&d, 0.0005, 3, clock: &t)+ #expect(feed(&d, 0.05, 0.03, clock: &t).isEmpty)+ #expect(feed(&d, 0.0005, 2, clock: &t).isEmpty)+ }++ /// The echo-cancelled voice comes through in pieces: short gaps don't reset the onset or end it.+ @Test func gapsBetweenWordsKeepOneSentence() {+ var d = HandsFreeDetector(), t = 0.0+ _ = feed(&d, 0.0005, 3, clock: &t)+ var events: [HandsFreeDetector.Event] = []+ for _ in 0..<6 {+ events += feed(&d, 0.05, 0.06, clock: &t).map(\.0)+ events += feed(&d, 0.0005, 0.1, clock: &t).map(\.0)+ }+ for _ in 0..<5 {+ events += feed(&d, 0.05, 0.3, clock: &t).map(\.0)+ events += feed(&d, 0.0005, 0.6, clock: &t).map(\.0)+ }+ events += feed(&d, 0.0005, 1.5, clock: &t).map(\.0)+ #expect(events == [.began, .ended(cut: false)])+ }++ @Test func aLongMonologueIsCutAndGoesOn() {+ var d = HandsFreeDetector(), t = 0.0+ _ = feed(&d, 0.0005, 3, clock: &t)+ // Speech with a short gap every 0.4 s, as words have.+ var events: [HandsFreeDetector.Event] = []+ for _ in 0..<110 {+ events += feed(&d, 0.05, 0.3, clock: &t).map(\.0)+ events += feed(&d, 0.0005, 0.1, clock: &t).map(\.0)+ }+ #expect(events == [.began, .ended(cut: true), .ended(cut: true)])+ #expect(d.talking)+ }++ /// A noisy room raises the line: its hum is not a voice.+ @Test func theLineFollowsTheRoom() {+ var d = HandsFreeDetector(), t = 0.0+ #expect(feed(&d, 0.008, 5, clock: &t).isEmpty)+ #expect(d.line > 0.03)+ #expect(feed(&d, 0.1, 1, clock: &t).map(\.0) == [.began])+ }++ /// What Ming made of the meeting's leftovers (100 % on the speakers, nobody talking) is found in the+ /// meeting's translated lines around it; my own sentence over the same meeting is not.+ @Test func theMeetingsOwnWordsAreItsEcho() {+ let meeting: [EchoMatch.Heard] = [+ .init(text: "Our revenue grew 12% this quarter, mostly from enterprise customers in Europe.", start: 0, end: 4),+ .init(text: "我们的营收本季度增长了12%,主要来自欧洲的企业客户。营销支出低于计划,我们还招聘了四名工程师。", start: 0, end: 7),+ .init(text: "下个月我们将上线新的定价页面,并回顾下半年的招聘计划。", start: 8, end: 12),+ ]+ #expect(EchoMatch.isEcho(.init(text: "营收增长;四名工程师;下半年", start: 3, end: 9), online: meeting))+ #expect(!EchoMatch.isEcho(.init(text: "我同意这个数字,设计那个岗位很急,周四之前我会回复。", start: 3, end: 9), online: meeting))+ }+}diff --git a/tools/README.md b/tools/README.mdindex aaff152..6c8ab56 100644--- a/tools/README.md+++ b/tools/README.md@@ -18,7 +18,7 @@- 快捷键:`talkKey:right` 或 `talkKey:<keyCode>:<Carbon 修饰键>` 换说话键(被拒的原因写进日志),`toggleKey:…` 同理,`shortcuts` 把当前状态写进日志- 字幕条:`frame` 把位置写进日志,`place:x,y,宽,字号` 摆到指定位置- 系统麦克风:`sysMic` 把状态、默认输入、要换回的麦克风和知了实际在录的麦克风写进日志,`sysMicSet:<设备名片段>` 假装别人改了系统麦克风,`sysMicRestore` 还原,`sysMicSwitch` 换成虚拟麦克风,`sysMicAuto:<on|off>`,`speakMic:<设备名片段>` 固定知了用的麦克风(留空 = 自动)。会改本机的系统麦克风:测完 `sysMicRestore` 或退出 App- - 说话同传:`speakOn` / `speakOff` 开关,`speakAsk[:off]` 面板里第一次打开时的确认卡,`speakConfirmed:<on|off>` 是否已确认过,`speakFile:<音频>` 把文件按实时速度当作麦克风输入,`speakOut:<路径>` 把译文语音另存一份,`speakOutput:<设备名片段>` 改输出设备(留空 = 虚拟麦克风),`speakVP:<on|off>` 按键说话时用不用带回声消除的麦克风(默认开;日志 `voice mic: ready`、`speak: mic with echo cancellation`),`talkDown` / `talkUp` 用真麦克风按住、松开说话键(日志 `speak: on-device heard … Ming …`、没人说话时 `nothing said in the press`;每次按键都写 `speak: press of … s, voiced … s, quiet … dBFS, line … dBFS`,声音偏小但本机识别听出一句时 `quiet press, but the on-device recognizer heard … chars: sending`)+ - 说话同传:`speakOn` / `speakOff` 开关,`speakAsk[:off]` 面板里第一次打开时的确认卡,`speakConfirmed:<on|off>` 是否已确认过,`speakFile:<音频>` 把文件按实时速度当作麦克风输入,`speakOut:<路径>` 把译文语音另存一份,`speakOutput:<设备名片段>` 改输出设备(留空 = 虚拟麦克风),`speakVP:<on|off>` 按键说话时用不用带回声消除的麦克风(默认开;日志 `voice mic: ready`、`speak: mic with echo cancellation`),`talkDown` / `talkUp` 用真麦克风按住、松开说话键(日志 `speak: on-device heard … Ming …`、没人说话时 `nothing said in the press`;每次按键都写 `speak: press of … s, voiced … s, quiet … dBFS, line … dBFS`,声音偏小但本机识别听出一句时 `quiet press, but the on-device recognizer heard … chars: sending`),`handsFree:<on|off>` 改“不用按键”(只在听会议时运行;日志 `hands-free: listening`、`voice began`、`sentence of … s`,没发出去时 `only … s of voice` / `… chars, too short` / `the meeting's own words`),`handsFreeDump:<路径>` 把回声消除后的麦克风写成 16 kHz float32 原始文件(留空停止)- 试一句:`speakTest:sample`(Mac 读一句示例)或 `speakTest:voice`(再发 `speakTestBegin` / `speakTestEnd` 当作按住、松开),结果以 `speak test:` 写进日志;`speakTestState`、`speakTestRender:<png>`、`speakTestClose`- 识别引擎:`recognizer:legacy` 在 macOS 26 上改用 14 / 15 的识别(`SFSpeechRecognizer`,第一次会要“语音识别”权限),`recognizer:cloud` 像 Intel Mac 那样全部交给 Ling 听(没有 key 就听不了),`recognizer:auto` 换回;下一次开始听起生效(或启动时 `open --env CICADA_RECOGNIZER=legacy`),日志里 `transcriber started recognizer=…`;`recordTrack:off` 让会议记录不再另用一遍不切句的识别(下一次开始听起生效,对比准确度用;`open --env CICADA_RECORD_TRACK=off` 同理),`recordState` 把还在校准的句数写进日志,打开 `debug` 后日志里有 `RECORD` 和 `REFINE`- 多开:两边都设 `CICADA_DEBUG_CHANNEL=x`(`open -n --env CICADA_DEBUG_CHANNEL=x build/Cicada.app`),命令只发给这一份,日志在 `/tmp/livesubs-dev-debug-x.log`