知了 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
fix: other apps hear the built-in mic again while Interpreting is on
wquguru4cbc0a19c12b
diff --git a/Sources/Cicada/SpeakEngine.swift b/Sources/Cicada/SpeakEngine.swiftindex a272d76..426b545 100644--- a/Sources/Cicada/SpeakEngine.swift+++ b/Sources/Cicada/SpeakEngine.swift@@ -102,7 +102,13 @@ final class SpeakEngine {var roomLanguage: (() -> String?)?let settings: AppSettings- private(set) var phase: Phase = .idle+ private(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() } }+ }private var mic = AVAudioEngine()/// The mic with echo cancellation, shared with 电脑和会议室's room (`VoiceMic`): used when@@ -112,11 +118,7 @@ final class SpeakEngine {/// plain mic, Ming took the meeting's own English for what I said and sent it back into the/// meeting, every press, even one nobody spoke in; through the unit my sentences came through/// whole (an ESP32 speaker 10 cm from the mic as me, the MacBook's speakers at 56 %).- var echoCancel = true {- didSet {- if echoCancel, let d = echoInput { voiceMic.prepare(input: d) } else if !echoCancel, !voiceMic.inUse { voiceMic.release() }- }- }+ var echoCancel = true/// The real mic to cancel the echo for; nil when it is unknown or virtual (nothing to cancel there).private var echoInput: AudioObjectID? {// The plain room mic open: the unit readied after each press made it start again, which@@ -228,7 +230,6 @@ final class SpeakEngine {analyzerFormat = await Recognition.format(lang.locale, drafts: true)analyzerLocale = lang.localedebugLog("speak transcriber ready locale=\(lang.locale)")- if echoCancel, let d = echoInput { voiceMic.prepare(input: d) }} catch {debugLog("speak transcriber failed: \(error)")onStatus?(L("无法准备语音识别:\(error.localizedDescription)"))@@ -374,20 +375,40 @@ final class SpeakEngine {private func startMic(format: AVAudioFormat, input cont: RecognitionStream) {if echoCancel || voiceMic.inUse, let device = echoInput {- let conv = converter- let queue = micQueue- feeding = true- let started = voiceMic.attach("press", input: device) { [weak self] buf in- queue.async {- guard let self, self.feeding, let c = conv.convert(buf, to: format) else { return }- cont.append(c)- self.recordMic(c)- self.keepForMing(c)- }+ // Made now, not ahead (see `VoiceMic`): the press hears from when it is ready.+ pressPlain = false+ let press = pressStarted+ voiceMic.prepare(input: device) { [weak self] ok in+ Task { @MainActor in self?.attachPress(press, ok: ok, device: device, format: format, input: cont) }+ }+ return+ }+ startPlainMic(format: format, input: cont)+ }++ private func attachPress(_ press: Date, ok: Bool, device: AudioObjectID, format: AVAudioFormat, input cont: RecognitionStream) {+ // The key was let go of before the unit was ready: the phase going idle found nothing to give back.+ guard phase == .listening, pressStarted == press, utterance?.input === cont else {+ if phase == .idle, !voiceMic.inUse { voiceMic.release() }+ return+ }+ let conv = converter+ let queue = micQueue+ feeding = true+ let started = ok && voiceMic.attach("press", input: device) { [weak self] buf in+ queue.async {+ guard let self, self.feeding, let c = conv.convert(buf, to: format) else { return }+ cont.append(c)+ self.recordMic(c)+ self.keepForMing(c)}- debugLog("speak: mic \(started ? "with echo cancellation" : "plain, echo cancellation not ready")")- if started { pressPlain = false; return }}+ debugLog(String(format: "speak: mic %@ after %.2f s", started ? "with echo cancellation" : "plain, echo cancellation failed",+ Date().timeIntervalSince(press)))+ if !started { startPlainMic(format: format, input: cont) }+ }++ private func startPlainMic(format: AVAudioFormat, input cont: RecognitionStream) {pressPlain = true// A unit left over (toggled off mid-press, a virtual mic) would starve the plain mic; one the// room is using stays (the talk key is then on another mic).@@ -473,7 +494,6 @@ final class SpeakEngine {mic.inputNode.removeTap(onBus: 0)mic.stop()}- if echoCancel, let d = echoInput { voiceMic.prepare(input: d) } else if !echoCancel, !voiceMic.inUse { voiceMic.release() }}private func finishUtterance() {diff --git a/Sources/Cicada/VoiceMic.swift b/Sources/Cicada/VoiceMic.swiftindex 2102ab1..17ab116 100644--- a/Sources/Cicada/VoiceMic.swift+++ b/Sources/Cicada/VoiceMic.swift@@ -11,10 +11,12 @@ import CoreAudio/// press) share it as consumers, and it runs while anyone is attached.////// The raw unit, because AVAudioEngine's voice processing fails ('bfmt') when the default input is-/// the virtual mic, which 同声传译 makes it. Making the unit takes ~1.8 s, so it is made ahead and-/// only started (~40 ms) and stopped per press; made but stopped, it doesn't hold the mic open, but-/// it does starve AVAudioEngine's input on the same mic (−56 dB peaks): it is let go of before the-/// plain mic is used.+/// the virtual mic, which 同声传译 makes it. Not made ahead: while a unit exists in this process, even+/// stopped, uninitialized or with no device set, every other app's input on the Mac hears almost+/// nothing (measured from another process: −60 to −72 dB instead of −17 dB; Teams heard nobody,+/// issue #24). So it is made when needed (1–1.7 s, nearly all of it in AudioComponentInstanceNew;+/// 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.final class VoiceMic: @unchecked Sendable {@@ -96,7 +98,7 @@ final class VoiceMic: @unchecked Sendable {/// `key` hears `input` from now on, if the unit is ready for it and the current output (it starts/// with the first consumer). Otherwise false: the caller uses the plain mic this time, after- /// `release` when nobody else is attached; a new unit is made later, not while the plain mic runs.+ /// `release` when nobody else is attached.func attach(_ key: String, input: AudioObjectID, processing: Bool = true, onAudio: @escaping (AVAudioPCMBuffer) -> Void) -> Bool {guard let output = SystemAudioTap.defaultOutputDevice() else { return false }lock.lock()@@ -117,7 +119,7 @@ final class VoiceMic: @unchecked Sendable {return true}- /// `key` stops hearing; the unit stops with the last consumer.+ /// `key` stops hearing; the unit stops with the last consumer, and is kept until `release`.func detach(_ key: String) {lock.lock()guard consumers.removeValue(forKey: key) != nil else { lock.unlock(); return }@@ -157,7 +159,8 @@ final class VoiceMic: @unchecked Sendable {debugLog("voice mic: processing \(bypass ? "off" : "on") (running \(running), stop \(stopped), set \(status), start \(started))")}- /// Lets go of the unit (not while anyone is attached), so the plain mic hears again.+ /// Lets go of the unit (not while anyone is attached), so the mic hears again, here and in+ /// every other app.func release() {let old: AudioUnit? = lock.withLock {guard consumers.isEmpty, let u = unit else { return nil }@@ -257,7 +260,9 @@ final class EchoCancelledRoomMic: AudioSource, @unchecked Sendable {func start() throws {mic.prepare(input: device.id) { [weak self] ok in- guard let self, !self.lock.withLock({ self.stopped }) else { return }+ guard let self else { return }+ // Stopped while it was being made: nobody else may be left to give it back.+ guard !self.lock.withLock({ self.stopped }) else { self.mic.release(); return }let attached = ok && self.mic.attach("room", input: self.device.id, processing: self.processing) { [weak self] buf in self?.deliver(buf) }if !attached {debugLog("room mic: echo cancellation unavailable, plain mic instead")@@ -271,6 +276,8 @@ final class EchoCancelledRoomMic: AudioSource, @unchecked Sendable {func stop() {lock.withLock { stopped = true }mic.detach("room")+ // Kept, it would silence the mic for every other app (a press still using it keeps it).+ mic.release()}private func deliver(_ buf: AVAudioPCMBuffer) {diff --git a/site/changelog.json b/site/changelog.jsonindex a72177a..600b5b1 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -69,6 +69,14 @@],"title": "对方从扬声器说话时按住说话,说的话照样翻译发出去。","text": "以前电脑在放会议声音时按住说话,会因为怕把对方的声音当成你说的,提示“对方在说话时说的,没有说出去”。现在按住说话时麦克风经过 Windows 的回声消除,对方的声音被去掉,你说的照常发出去。需要 Windows 11 和带回声消除的麦克风;没有的电脑还是和以前一样。"+ },+ {+ "kind": "fixed",+ "platforms": [+ "mac"+ ],+ "title": "打开同声传译后,Teams 等其他应用又能用内置麦克风了。",+ "text": "以前打开同声传译,知了会提前备好回声消除,哪怕没按发言键,其他应用从内置麦克风也几乎收不到声音,退出知了才恢复。现在只在按住发言键、到这句译文说完为止才占用;代价是按下后要等 1 到 2 秒才开始收音。"}]},