Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat: Listen to a meeting in the room through the Mac's microphone (听哪里 › 会议室)

wquguru9236b267fc15
diff --git a/README.en.md b/README.en.md
index 89940d8..d59acf2 100644
--- a/README.en.md
+++ b/README.en.md
@@ -40,6 +40,10 @@ While the meeting runs, the notes window organizes a summary, topics and key poi
Cicada detects the spoken language on device within seconds and translates into your system language, and pressing `⌃⌥S` switches between the notes window, a compact subtitle bar, and hidden. The subtitle bar appears only when someone speaks and turns see-through under your pointer so you can click right through it.
+### Meetings in the room
+
+For a meeting around a table, set **Listen to** in the menu bar panel to **Room** and Cicada listens through the Mac's microphone, with the same subtitles, notes and records as an online meeting. Speak-back then reads the translation out of the speakers, no virtual mic needed, and the microphone stops listening while it does so the translation isn't recorded as someone else. If nothing plays on the Mac for a minute while it listens to the computer, the panel asks whether to listen to the room instead; every launch starts with the computer again.
+
### Speak back in their language
Hold the right `⌥` key and speak so the room hears your translated voice through BlackHole 2ch, a virtual microphone you can install from the app with one click and that Cicada switches to automatically while interpreting is on. With a Ling API key, the other side hears natural Ming voices or a clone of your own voice from an 8 to 30 second sample, and without a key it uses macOS system voices.
@@ -65,7 +69,7 @@ Cicada asks for a permission only when you use the feature that needs it, and ev
| Permission | What it's for | When it's asked | Without it |
|---|---|---|---|
| System audio recording (Screen & System Audio Recording) | Hearing what your Mac plays, for subtitles. Never records the screen or its own sound | Onboarding step 1, or the first time it listens | No subtitles or notes |
-| Microphone | Recording only while you hold the talk key, for speak-back | When you turn on speak-back | No speak-back |
+| Microphone | Your voice while you hold the talk key, for speak-back; the people in the room when **Listen to** is **Room** | When you turn on speak-back or first listen to the room | No speak-back, no listening to the room |
| Input Monitoring | Only to tell whether the right `⌥` was pressed on its own (listen-only; nothing is blocked or logged) | The first time you talk with right `⌥` | Pick a `⌃`/`⌘` combination in Settings instead; it needs no permission |
| Administrator password | Installing the BlackHole 2ch virtual microphone and restarting the system audio service | When you click Install in onboarding or Settings, once | The room can't hear your translation; everything else works |
diff --git a/README.md b/README.md
index 1e7a801..ae77af3 100644
--- a/README.md
+++ b/README.md
@@ -40,6 +40,10 @@
对方开口几秒钟就能在本地自动认出语言并翻成你的系统语言,按 `⌃⌥S` 可以在纪要窗口、字幕条和不显示之间切换。字幕条只在有人说话时出现,鼠标划过时自动变透明,不会挡住底下的按钮。
+### 线下会议
+
+在会议室里开会时,把菜单栏面板的“听哪里”改成“会议室”,知了就用 Mac 的麦克风听桌边的人说话,字幕、纪要和会议记录跟线上会议一样。同声传译这时从扬声器念出译文,不需要虚拟麦克风,念的时候麦克风暂时不听,不会把译文再记成别人的话。听电脑声音时如果 1 分钟都没有声音,面板会问一句要不要改听会议室;每次启动都回到听电脑声音。
+
### 同声传译
按住键盘右边的 `⌥` 键说话,对方在会议软件里就能直接听到翻译后的语音,打开同声传译时知了会自动把系统麦克风切到一键安装的虚拟驱动 BlackHole 2ch。填了 Ling API key 后可以用自然人声或用 8 到 30 秒录音克隆你自己的声音,不填也能用 Mac 自带语音。
@@ -65,7 +69,7 @@
| 权限 | 用来做什么 | 什么时候问 | 不给的话 |
|---|---|---|---|
| 录制系统声音(屏幕与系统录音) | 听 Mac 正在播放的声音来出字幕,不录屏幕,也不听知了自己的声音 | 新手引导第一步,或第一次开始听 | 字幕和纪要都用不了 |
-| 麦克风 | 只在你按住说话键时录音,用来做同声传译 | 打开同声传译时 | 只是不能说话翻译 |
+| 麦克风 | 按住说话键时录你说的话做同声传译;“听哪里”选了“会议室”时听屋里的人 | 打开同声传译或第一次听会议室时 | 不能说话翻译,也不能听会议室 |
| 输入监控 | 只用来判断右 `⌥` 是否被单独按下(只监听、不拦截、不记录别的按键) | 第一次用右 `⌥` 说话时 | 在设置里改成 `⌃`/`⌘` 组合键,就不需要这个权限 |
| 管理员密码 | 安装虚拟麦克风 BlackHole 2ch,并重启系统音频服务 | 在引导或设置里点“安装”时,只问一次 | 不能让对方听到翻译,其余照常 |
diff --git a/Resources/Info.plist b/Resources/Info.plist
index 8593aee..56468c1 100644
--- a/Resources/Info.plist
+++ b/Resources/Info.plist
@@ -45,7 +45,7 @@
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 知了 Cicada</string>
<key>NSMicrophoneUsageDescription</key>
- <string>While you hold the talk key, Cicada uses the microphone to translate what you say into the other side's language.</string>
+ <string>While you hold the talk key, Cicada uses the microphone to translate what you say into the other side's language. When it listens to a meeting in the room, the microphone hears the people there.</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>Cicada uses speech recognition to turn audio into text.</string>
</dict>
diff --git a/Resources/en.lproj/InfoPlist.strings b/Resources/en.lproj/InfoPlist.strings
index f50ae2c..671a37e 100644
--- a/Resources/en.lproj/InfoPlist.strings
+++ b/Resources/en.lproj/InfoPlist.strings
@@ -1,5 +1,5 @@
CFBundleName = "Cicada";
CFBundleDisplayName = "Cicada";
NSAudioCaptureUsageDescription = "Cicada reads the sound your Mac is playing to make live subtitles.";
-NSMicrophoneUsageDescription = "While you hold the talk key, Cicada uses the microphone to translate what you say into the other side's language.";
+NSMicrophoneUsageDescription = "While you hold the talk key, Cicada uses the microphone to translate what you say into the other side's language. When it listens to a meeting in the room, the microphone hears the people there.";
NSSpeechRecognitionUsageDescription = "Cicada uses speech recognition to turn audio into text.";
diff --git a/Resources/ja.lproj/InfoPlist.strings b/Resources/ja.lproj/InfoPlist.strings
index e94f7bf..96ca6e1 100644
--- a/Resources/ja.lproj/InfoPlist.strings
+++ b/Resources/ja.lproj/InfoPlist.strings
@@ -1,5 +1,5 @@
CFBundleName = "Cicada";
CFBundleDisplayName = "Cicada";
NSAudioCaptureUsageDescription = "ライブ字幕を作るため、Cicada は Mac で再生中の音声を読み取ります。";
-NSMicrophoneUsageDescription = "話すキーを押している間、Cicada はマイクを使ってあなたの言葉を相手の言語に翻訳します。";
+NSMicrophoneUsageDescription = "話すキーを押している間、Cicada はマイクを使ってあなたの言葉を相手の言語に翻訳します。会議室を聞くときは、マイクでその場の人の声を聞きます。";
NSSpeechRecognitionUsageDescription = "Cicada は音声をテキストにするために音声認識を使います。";
diff --git a/Resources/ko.lproj/InfoPlist.strings b/Resources/ko.lproj/InfoPlist.strings
index 46ac4c8..6ae5641 100644
--- a/Resources/ko.lproj/InfoPlist.strings
+++ b/Resources/ko.lproj/InfoPlist.strings
@@ -1,5 +1,5 @@
CFBundleName = "Cicada";
CFBundleDisplayName = "Cicada";
NSAudioCaptureUsageDescription = "실시간 자막을 만들기 위해 Cicada가 Mac에서 재생 중인 소리를 읽습니다.";
-NSMicrophoneUsageDescription = "말하기 키를 누르고 있는 동안 Cicada가 마이크로 내 말을 상대의 언어로 번역합니다.";
+NSMicrophoneUsageDescription = "말하기 키를 누르고 있는 동안 Cicada가 마이크로 내 말을 상대의 언어로 번역합니다. 회의실을 들을 때는 마이크로 그 자리에 있는 사람들의 말을 듣습니다.";
NSSpeechRecognitionUsageDescription = "Cicada는 음성을 텍스트로 바꾸기 위해 음성 인식을 사용합니다.";
diff --git a/Resources/zh-Hans.lproj/InfoPlist.strings b/Resources/zh-Hans.lproj/InfoPlist.strings
index 86acca6..1b71e3b 100644
--- a/Resources/zh-Hans.lproj/InfoPlist.strings
+++ b/Resources/zh-Hans.lproj/InfoPlist.strings
@@ -1,5 +1,5 @@
CFBundleName = "知了";
CFBundleDisplayName = "知了";
NSAudioCaptureUsageDescription = "知了需要读取系统正在播放的声音,用于生成实时字幕。";
-NSMicrophoneUsageDescription = "按住快捷键说话时,知了需要麦克风把你的话翻译成对方的语言。";
+NSMicrophoneUsageDescription = "按住快捷键说话时,知了需要麦克风把你的话翻译成对方的语言;听会议室时,麦克风用来听屋里的人说话。";
NSSpeechRecognitionUsageDescription = "知了需要语音识别权限,把音频转成文字。";
diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swift
index 9e4bbff..e4eb93c 100644
--- a/Sources/LiveSubs/AppModel.swift
+++ b/Sources/LiveSubs/AppModel.swift
@@ -122,6 +122,8 @@ final class AppModel: ObservableObject {
var openMainWindow: (() -> Void)?
var openSettingsWindow: (() -> Void)?
var showPanel: (() -> Void)?
+ /// Opens the menu bar panel, leaving it open if it already is.
+ var openPanel: (() -> Void)?
private var lineForSegment: [Int: String] = [:]
private var lineCounter = 0
@@ -201,10 +203,12 @@ final class AppModel: ObservableObject {
}
speak.roomLanguage = { [weak self] in self?.listen.activeLang?.code }
speak.inputDevice = { [weak self] in self?.systemMic.recordingDevice }
+ listen.roomDevice = { AudioDevices.roomMic }
applyVoice()
speak.onStatus = { [weak self] text in self?.status = text }
speak.onLive = { [weak self] phase, src, dst in
guard let self else { return }
+ self.muteRoomWhileSpeaking(phase)
self.speakPhase = phase
// A 试一句 rehearsal shows in its own sheet: no notes window, caption or subtitle bar.
if self.speakTester.busy { return }
@@ -278,6 +282,9 @@ final class AppModel: ObservableObject {
func launch() async {
await listen.refreshInstalledLocales()
refresh()
+ // Listening starts by itself at launch: never with the microphone open. 会议室 is chosen
+ // for the meeting at hand, not kept for the next login.
+ if settings.listensToRoom { settings.listenSource = "system" }
start()
if settings.speakEnabled { enableSpeaking(true) }
}
@@ -285,8 +292,8 @@ final class AppModel: ObservableObject {
func refresh() {
running = listen.isRunning
// Once the tap has run, the permission is there: pausing doesn't take it away.
- systemAudioOK = systemAudioOK || listen.isRunning
- summary = listen.languageSummary()
+ systemAudioOK = systemAudioOK || (listen.isRunning && !settings.listensToRoom)
+ summary = settings.listensToRoom ? L("会议室 · \(listen.languageSummary())") : listen.languageSummary()
candidates = listen.candidates
installed = listen.installedLocales
let ask = listen.asksLanguage ? listen.askChoices : []
@@ -317,7 +324,15 @@ final class AppModel: ObservableObject {
if mic != micStatus { micStatus = mic }
let devices = AudioDevices.outputs()
if devices.map(\.uid) != outputs.map(\.uid) { outputs = devices }
- if listen.isRunning && !systemAudioOK { systemAudioOK = true }
+ if listen.isRunning && !settings.listensToRoom && !systemAudioOK { systemAudioOK = true }
+ // Refused (in the prompt, or turned off in System Settings later): the tap would only hear silence.
+ if let p = SystemAudioPermission.status() {
+ let ok = p == .granted || (p == .unknown && systemAudioOK)
+ if ok != systemAudioOK { systemAudioOK = ok }
+ if (p == .denied) != systemAudioRefused { systemAudioRefused = p == .denied }
+ }
+ let speech = Recognition.ready
+ if speech != speechOK { speechOK = speech }
refreshMicUsers()
refreshSystemMic()
}
@@ -326,7 +341,8 @@ final class AppModel: ObservableObject {
/// Switching the system mic only helps when our voice goes into the virtual mic.
var wantsSystemMic: Bool {
- guard settings.speakEnabled, settings.autoSystemMic, virtualMic != nil else { return false }
+ // In 会议室 the translation is read out of the speakers: nothing goes into a call.
+ guard settings.speakEnabled, settings.autoSystemMic, !settings.listensToRoom, virtualMic != nil else { return false }
return settings.speakOutput.isEmpty || (outputs.first { $0.uid == settings.speakOutput }?.isVirtualMic ?? true)
}
@@ -459,6 +475,7 @@ final class AppModel: ObservableObject {
lastHeard = nil
heldJoin = nil
speechHeard = false
+ roomPromptDismissed = false
meetingSubtitles = nil
autoEnded = false
endWatch = MeetingEndWatch(config: endConfig, start: Date())
@@ -468,6 +485,7 @@ final class AppModel: ObservableObject {
speak.setRecording(store.micAudioURL(session.id))
}
listen.start()
+ if settings.listensToRoom { store.markLiveInRoom() }
notes.begin(session.id)
if listen.isRunning {
showDisplay()
@@ -654,6 +672,44 @@ final class AppModel: ObservableObject {
// MARK: Settings actions
+ /// 听哪里 in the panel: "system" or "room".
+ var listenSourceSelection: String {
+ get { settings.listenSource }
+ set {
+ guard newValue != settings.listenSource else { return }
+ settings.listenSource = newValue == "room" ? "room" : "system"
+ roomPromptDismissed = true
+ if listen.isRunning && settings.listensToRoom { store.markLiveInRoom() }
+ listen.listenSourceChanged()
+ applySystemMic()
+ refreshMicUsers()
+ refresh()
+ objectWillChange.send()
+ }
+ }
+
+ /// 改听会议室 / 不是 on the 在会议室里开会? strip.
+ func answerRoomPrompt(_ room: Bool) {
+ debugLog("room prompt answered: \(room ? "room" : "no")")
+ roomPromptDismissed = true
+ if room { listenSourceSelection = "room" } else { refresh() }
+ }
+
+ /// The room mic hears silence from the talk key going down until the translation has been
+ /// read out, and a moment after, so neither your voice nor the Mac's comes back as the room.
+ private func muteRoomWhileSpeaking(_ phase: SpeakEngine.Phase) {
+ if phase != .idle {
+ listen.setRoomMuted(true)
+ return
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { [weak self] in
+ MainActor.assumeIsolated {
+ guard let self, self.speak.phase == .idle else { return }
+ self.listen.setRoomMuted(false)
+ }
+ }
+ }
+
var sourceSelection: String {
get {
if case .fixed(let l) = settings.sourceMode { return l.locale }
@@ -868,6 +924,8 @@ final class AppModel: ObservableObject {
if let reason { autoEnd(reason, watch: w) }
} else if !listen.isRunning, autoEnded, settings.endWithApp, !(fakeCalls ?? MicUsers.currentCalls()).isEmpty {
debugLog("meeting end: a meeting app started a call, starting a new meeting")
+ // A call is on the Mac, not in the room.
+ if settings.listensToRoom { settings.listenSource = "system"; applySystemMic() }
start()
}
}
@@ -1108,6 +1166,9 @@ final class AppModel: ObservableObject {
case "pickLanguage":
if let lang = sourceLanguages.first(where: { $0.locale == arg }) { listen.pickLanguage(lang) }
case "stop": stop()
+ case "source": sourceSelection = arg
+ case "listenSource": listenSourceSelection = arg
+ case "roomPrompt": answerRoomPrompt(arg == "room")
case "open": openMainWindow?()
case "panel": showPanel?()
case "onboarding":
@@ -1423,6 +1484,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
model.openMainWindow = { [weak self] in self?.showMainWindow() }
model.openSettingsWindow = { [weak self] in self?.showSettingsWindow() }
model.showPanel = { [weak self] in self?.togglePopover() }
+ model.openPanel = { [weak self] in if self?.popover.isShown == false { self?.togglePopover() } }
model.openOnboarding = { [weak self] in self?.showOnboarding() }
runningObserver = model.$running.combineLatest(model.updates.$update).sink { [weak self] live, update in
self?.statusItem.button?.image = BrandImage.menuBar(live: live, badge: update != nil)
diff --git a/Sources/LiveSubs/AudioRouter.swift b/Sources/LiveSubs/AudioRouter.swift
index c5f2215..beb282c 100644
--- a/Sources/LiveSubs/AudioRouter.swift
+++ b/Sources/LiveSubs/AudioRouter.swift
@@ -107,8 +107,12 @@ final class AudioRouter: @unchecked Sendable {
private var recordURL: URL?
private var recorder: AVAudioFile?
- /// Below this RMS the block counts as silence (≈ -40 dBFS).
- private let voiceThreshold: Float = 0.01
+ /// When a block counts as speech (pauses, language detection, the silence that ends a meeting).
+ private var gate = VoiceGate()
+ func setRoomGate(_ on: Bool) {
+ queue.async { [self] in gate = VoiceGate(adaptive: on) }
+ }
+ func gateThreshold() -> Float { queue.sync { gate.threshold } }
/// Loudest buffer since the last `takeLevel()`, for the level meter.
private var peak: Float = 0
@@ -131,7 +135,7 @@ final class AudioRouter: @unchecked Sendable {
let rms = (sum / Float(n)).squareRoot()
peak = max(peak, rms)
let seconds = Double(n) / mono.format.sampleRate
- let voiced = rms >= voiceThreshold
+ let voiced = gate.voiced(rms)
if voiced {
if silenceRun >= 0.12, sink != nil { pause = (fed, silenceRun) }
if silenceRun >= Self.gapSeconds { sinceGap = 0 }
diff --git a/Sources/LiveSubs/ListenEngine.swift b/Sources/LiveSubs/ListenEngine.swift
index 8a47c16..5ad2f14 100644
--- a/Sources/LiveSubs/ListenEngine.swift
+++ b/Sources/LiveSubs/ListenEngine.swift
@@ -280,7 +280,8 @@ final class ListenEngine {
// No model at all: start with the likeliest; the second follows in the background.
initial = candidates.first(where: { $0.locale == last }) ?? candidates.first ?? likely.first ?? sourceLanguages[0]
}
- setStatus(L("正在听"))
+ // 会议室 the first time: nothing is heard until macOS's microphone question is answered.
+ setStatus(audioTap == nil ? L("等你允许使用麦克风") : L("正在听"))
Task { await switchTranscriber(to: initial) }
fetchSecondModel(besides: initial)
}
@@ -331,13 +332,21 @@ final class ListenEngine {
@discardableResult
private func startTap() -> Bool {
+ router.setRoomGate(settings.listensToRoom)
+ if settings.listensToRoom { return startRoomMic() }
+ if SystemAudioPermission.status() == .denied {
+ debugLog("audio tap: system audio recording was refused")
+ isRunning = false
+ setStatus(L("请在系统设置里允许“系统音频录制”,再重新打开知了"))
+ return false
+ }
let tap = SystemAudioTap()
let router = self.router
tap.onAudio = { pcm in router.push(pcm) }
do {
try tap.start()
audioTap = tap
- debugLog("audio tap started")
+ debugLog("audio tap started, permission \(SystemAudioPermission.status().map { "\($0)" } ?? "unreadable")")
return true
} catch {
debugLog("audio tap start failed: \(error)")
@@ -347,6 +356,69 @@ final class ListenEngine {
}
}
+ /// 会议室. The first time, macOS asks for the microphone; listening starts once it is allowed.
+ private func startRoomMic() -> Bool {
+ switch AVCaptureDevice.authorizationStatus(for: .audio) {
+ case .authorized: break
+ case .notDetermined:
+ debugLog("room mic: asking for the microphone")
+ AVCaptureDevice.requestAccess(for: .audio) { [weak self] granted in
+ DispatchQueue.main.async {
+ MainActor.assumeIsolated {
+ guard let self, self.isRunning, self.settings.listensToRoom, self.audioTap == nil else { return }
+ if granted { if self.startRoomMic() { self.setStatus(L("正在听")) } } else { self.roomMicDenied() }
+ }
+ }
+ }
+ return true
+ default:
+ roomMicDenied()
+ return false
+ }
+ let mic = RoomMic(device: roomDevice?())
+ mic.muted = roomMuted
+ let router = self.router
+ mic.onAudio = { pcm in router.push(pcm) }
+ do {
+ try mic.start()
+ audioTap = mic
+ debugLog("room mic started: \(mic.deviceName)")
+ DispatchQueue.main.asyncAfter(deadline: .now() + 15) { [weak self] in
+ MainActor.assumeIsolated {
+ guard let self, self.audioTap === mic else { return }
+ debugLog("room mic speech threshold \(String(format: "%.4f", self.router.gateThreshold()))")
+ }
+ }
+ return true
+ } catch {
+ debugLog("room mic start failed: \(error)")
+ isRunning = false
+ setStatus(L("麦克风无法启动,请在系统设置里允许\(appDisplayName)使用麦克风"))
+ return false
+ }
+ }
+
+ private func roomMicDenied() {
+ debugLog("room mic: microphone not allowed")
+ if isRunning { stop() }
+ setStatus(L("麦克风无法启动,请在系统设置里允许\(appDisplayName)使用麦克风"))
+ }
+
+ /// While the Mac speaks into the room (or you hold the talk key) the room mic hears silence.
+ func setRoomMuted(_ on: Bool) {
+ guard on != roomMuted else { return }
+ roomMuted = on
+ (audioTap as? RoomMic)?.muted = on
+ if settings.listensToRoom { debugLog("room mic \(on ? "muted" : "open")") }
+ }
+
+ /// 听哪里 changed: while listening, the new source takes over in the same meeting.
+ func listenSourceChanged() {
+ debugLog("listen source=\(settings.listenSource)")
+ reconnectAudio()
+ onStateChange?()
+ }
+
// MARK: Settings changes
func sourceModeChanged() {
@@ -870,6 +942,24 @@ final class ListenEngine {
guard self.ticks % 4 == 0 else { return }
self.translateVolatile()
self.maybeDetectLanguage()
+ let silent = RoomPrompt.asks(room: self.settings.listensToRoom,
+ listened: Date().timeIntervalSince(self.startedAt),
+ voiced: self.router.stats().voicedTotal)
+ if silent != self.macSilent {
+ self.macSilent = silent
+ debugLog("mac silent \(silent)")
+ self.onStateChange?()
+ }
+ if self.ticks % 20 == 0 { self.checkDictation() }
+ // The fetch's progress, and 听不出 coming or going, redraw the windows.
+ let ask = self.asksLanguage
+ if ask != self.askShown || self.fetchingModel != nil {
+ if ask != self.askShown { debugLog("language ask \(ask ? "shown" : "hidden")") }
+ let flipped = ask != self.askShown
+ self.askShown = ask
+ self.onStateChange?()
+ if flipped { self.renderSubtitles() }
+ }
}
}
tickTimer = timer
diff --git a/Sources/LiveSubs/RoomMic.swift b/Sources/LiveSubs/RoomMic.swift
new file mode 100644
index 0000000..03872b9
--- /dev/null
+++ b/Sources/LiveSubs/RoomMic.swift
@@ -0,0 +1,218 @@
+import AVFoundation
+import CoreAudio
+
+// 会议室: listening to the people in the room through a real microphone instead of what the Mac
+// plays. Same shape as `SystemAudioTap` (mono buffers out), so the rest of listening is unchanged.
+
+protocol AudioSource: AnyObject {
+ var onAudio: ((AVAudioPCMBuffer) -> Void)? { get set }
+ func start() throws
+ func stop()
+}
+
+extension SystemAudioTap: AudioSource {}
+
+/// Which microphone hears the room.
+enum RoomMicPlan {
+ struct Input: Equatable {
+ let uid: String
+ var builtIn = false
+ var bluetooth = false
+ var virtual = false
+ }
+
+ /// The system default, unless it is the virtual mic (同声传译 makes it the default) or a
+ /// Bluetooth headset's (AirPods hear the wearer, not the table, and drop to call quality while
+ /// their mic is open); then the Mac's own microphone.
+ static func pick(defaultUID: String?, inputs: [Input]) -> String? {
+ if let d = inputs.first(where: { $0.uid == defaultUID }), !d.virtual, !d.bluetooth { return d.uid }
+ return inputs.first(where: \.builtIn)?.uid
+ ?? inputs.first(where: { !$0.virtual && !$0.bluetooth })?.uid
+ ?? inputs.first(where: { !$0.virtual })?.uid
+ }
+}
+
+/// When a block of audio counts as speech. The Mac's own audio is digital silence between words, so
+/// a fixed -40 dBFS works there. A room mic always hears the room (a fan, the street), and a voice
+/// across the table can be quieter than -40 dBFS: there the line sits at twice the room's own noise.
+/// The noise is the quietest moment of each second (the gaps between words, even while people talk
+/// on and on), taken low over the last half minute.
+struct VoiceGate {
+ static let fixed: Float = 0.01
+ static let lowest: Float = 0.0015
+ /// About a second of the mic's ~85 ms blocks.
+ static let blocksPerSecond = 12
+ var adaptive = false
+ private var quietest: [Float] = []
+ private var second: Float = .infinity
+ private var blocks = 0
+
+ init(adaptive: Bool = false) { self.adaptive = adaptive }
+
+ var threshold: Float {
+ guard adaptive else { return Self.fixed }
+ guard quietest.count >= 3 else { return 0.004 }
+ let floor = quietest.sorted()[quietest.count / 5]
+ return min(Self.fixed, max(Self.lowest, floor * 2))
+ }
+
+ mutating func voiced(_ rms: Float) -> Bool {
+ let on = rms >= threshold
+ guard adaptive else { return on }
+ second = min(second, rms)
+ blocks += 1
+ if blocks >= Self.blocksPerSecond {
+ quietest.append(second)
+ if quietest.count > 30 { quietest.removeFirst() }
+ second = .infinity
+ blocks = 0
+ }
+ return on
+ }
+}
+
+/// 在会议室里开会?: asked when listening to the Mac and it has played nothing for a minute. It
+/// only reads the system audio already being listened to, so the microphone stays closed.
+enum RoomPrompt {
+ static let after = 60.0
+
+ static func asks(room: Bool, listened: Double, voiced: Double) -> Bool {
+ !room && listened >= after && voiced < 1
+ }
+
+ /// Shown in the panel: asked, not answered this meeting, and no meeting app in a call (early
+ /// in a call nobody may have spoken yet; that silence is not a meeting in the room).
+ static func shows(silent: Bool, answered: Bool, inCall: Bool) -> Bool {
+ silent && !answered && !inCall
+ }
+}
+
+extension AudioDevices {
+ static func transport(_ device: AudioObjectID) -> UInt32 {
+ var value: UInt32 = 0
+ var size = UInt32(MemoryLayout<UInt32>.size)
+ var addr = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyTransportType,
+ mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain)
+ AudioObjectGetPropertyData(device, &addr, 0, nil, &size, &value)
+ return value
+ }
+
+ /// The microphone `RoomMicPlan` picks among the Mac's inputs right now.
+ static var roomMic: OutputDevice? {
+ let all = inputs()
+ let plan = all.map { d -> RoomMicPlan.Input in
+ let t = transport(d.id)
+ return .init(uid: d.uid, builtIn: t == kAudioDeviceTransportTypeBuiltIn,
+ bluetooth: t == kAudioDeviceTransportTypeBluetooth || t == kAudioDeviceTransportTypeBluetoothLE,
+ virtual: d.isVirtualMic)
+ }
+ let uid = RoomMicPlan.pick(defaultUID: defaultInput?.uid, inputs: plan)
+ return all.first { $0.uid == uid }
+ }
+}
+
+/// A microphone as an audio source. While `muted`, silence goes on in its place: the Mac reading a
+/// translation aloud, or you holding the talk key, would otherwise come back as someone in the room.
+/// Silence rather than nothing keeps the recognizer's clock and the recording in step.
+final class RoomMic: AudioSource {
+ var onAudio: ((AVAudioPCMBuffer) -> Void)?
+ private var engine = AVAudioEngine()
+ private let device: OutputDevice?
+ private let lock = NSLock()
+ private var _muted = false
+ var muted: Bool {
+ get { lock.withLock { _muted } }
+ set { lock.withLock { _muted = newValue } }
+ }
+
+ private var configObserver: NSObjectProtocol?
+ private var defaultInputListener: AudioObjectPropertyListenerBlock?
+ private static var defaultInputAddress = AudioObjectPropertyAddress(
+ mSelector: kAudioHardwarePropertyDefaultInputDevice, mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain)
+
+ init(device: OutputDevice?) { self.device = device }
+
+ deinit {
+ if let configObserver { NotificationCenter.default.removeObserver(configObserver) }
+ if let defaultInputListener {
+ AudioObjectRemovePropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &Self.defaultInputAddress, .main, defaultInputListener)
+ }
+ }
+
+ /// Pinning the device on a fresh engine itself reports a configuration change: not a reason to go again.
+ private var startedAt = Date.distantPast
+
+ private func restart(_ why: String) {
+ guard !stopped, Date().timeIntervalSince(startedAt) > 1 else { return }
+ debugLog("room mic: \(why), restarting")
+ engine.inputNode.removeTap(onBus: 0)
+ engine.stop()
+ // A fresh engine: the old one still names the pinned device after moving off it, so
+ // pinning it again would be skipped.
+ if let configObserver { NotificationCenter.default.removeObserver(configObserver) }
+ configObserver = nil
+ engine = AVAudioEngine()
+ do { try start() } catch { debugLog("room mic restart failed: \(error)") }
+ }
+
+ var deviceName: String { device?.name ?? AudioDevices.inputDevice(of: engine) }
+
+ func start() throws {
+ startedAt = Date()
+ AudioDevices.pinInput(engine, to: device)
+ let input = engine.inputNode
+ let format = input.outputFormat(forBus: 0)
+ guard format.sampleRate > 0,
+ let mono = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: format.sampleRate, channels: 1, interleaved: false) else {
+ throw NSError(domain: "RoomMic", code: -1, userInfo: [NSLocalizedDescriptionKey: L("没有可用的麦克风")])
+ }
+ input.removeTap(onBus: 0)
+ input.installTap(onBus: 0, bufferSize: 4096, format: format) { [weak self] buf, _ in
+ guard let self, buf.frameLength > 0,
+ let out = AVAudioPCMBuffer(pcmFormat: mono, frameCapacity: buf.frameLength),
+ let dst = out.floatChannelData?[0] else { return }
+ out.frameLength = buf.frameLength
+ let n = Int(buf.frameLength)
+ let channels = Int(buf.format.channelCount)
+ if self.muted || channels == 0 || buf.floatChannelData == nil {
+ dst.update(repeating: 0, count: n)
+ } else if let src = buf.floatChannelData {
+ dst.update(from: src[0], count: n)
+ if channels > 1 {
+ for c in 1..<channels { for i in 0..<n { dst[i] += src[c][i] } }
+ let scale = 1 / Float(channels)
+ for i in 0..<n { dst[i] *= scale }
+ }
+ }
+ self.onAudio?(out)
+ }
+ engine.prepare()
+ try engine.start()
+ // A device coming or going, or another app switching the system mic, stops the engine
+ // without a word: start it again, or the room would go quiet for the rest of the meeting.
+ if configObserver == nil {
+ configObserver = NotificationCenter.default.addObserver(
+ forName: .AVAudioEngineConfigurationChange, object: engine, queue: .main) { [weak self] _ in
+ self?.restart("audio configuration changed")
+ }
+ }
+ // A new system default (AirPods connecting, another app switching to a virtual mic) stops
+ // the audio with no notification, though the engine still names the pinned device: start over.
+ if defaultInputListener == nil {
+ let listener: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
+ self?.restart("system input changed")
+ }
+ defaultInputListener = listener
+ AudioObjectAddPropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &Self.defaultInputAddress, .main, listener)
+ }
+ }
+
+ private var stopped = false
+
+ func stop() {
+ stopped = true
+ engine.inputNode.removeTap(onBus: 0)
+ engine.stop()
+ }
+}
diff --git a/Sources/LiveSubs/SessionStore.swift b/Sources/LiveSubs/SessionStore.swift
index e441342..c980adc 100644
--- a/Sources/LiveSubs/SessionStore.swift
+++ b/Sources/LiveSubs/SessionStore.swift
@@ -149,6 +149,13 @@ final class SessionStore: ObservableObject {
var liveStart: Date? { liveID.flatMap { index($0) }.map { sessions[$0].startedAt } }
+ /// The live meeting is (now) heard in the room: its record says 会议室.
+ func markLiveInRoom() {
+ guard let id = liveID, let i = index(id), sessions[i].room != true else { return }
+ sessions[i].room = true
+ scheduleSave(id)
+ }
+
func append(_ line: TranscriptLine) {
guard let id = liveID, let i = index(id) else { return }
sessions[i].lines.append(line)
diff --git a/Sources/LiveSubs/Settings.swift b/Sources/LiveSubs/Settings.swift
index 3cc82a8..7ce1c1d 100644
--- a/Sources/LiveSubs/Settings.swift
+++ b/Sources/LiveSubs/Settings.swift
@@ -118,6 +118,12 @@ final class AppSettings: ObservableObject {
}
/// Record per-sentence timings (never text) and show the 诊断 tab. On by default in dev builds.
+ /// 听哪里: "system" (what the Mac plays) or "room" (a real microphone, for a meeting in the room).
+ @Published var listenSource: String {
+ didSet { save() }
+ }
+ var listensToRoom: Bool { listenSource == "room" }
+
@Published var diagnostics: Bool {
didSet { save() }
}
@@ -155,6 +161,7 @@ final class AppSettings: ObservableObject {
endWithApp = defaults.object(forKey: "endWithApp") as? Bool ?? true
silenceEnd = defaults.string(forKey: "silenceEnd") ?? "prompt"
silenceMinutes = defaults.object(forKey: "silenceMinutes") as? Double ?? 10
+ listenSource = defaults.string(forKey: "listenSource") == "room" ? "room" : "system"
diagnostics = defaults.object(forKey: "diagnostics") as? Bool ?? DevBuild.isDev
notesCapturable = defaults.bool(forKey: "notesCapturable")
speakerVoices = defaults.bool(forKey: "speakerVoices")
@@ -187,6 +194,7 @@ final class AppSettings: ObservableObject {
defaults.set(endWithApp, forKey: "endWithApp")
defaults.set(silenceEnd, forKey: "silenceEnd")
defaults.set(silenceMinutes, forKey: "silenceMinutes")
+ defaults.set(listenSource, forKey: "listenSource")
defaults.set(diagnostics, forKey: "diagnostics")
defaults.set(notesCapturable, forKey: "notesCapturable")
defaults.set(speakerVoices, forKey: "speakerVoices")
diff --git a/Sources/LiveSubs/SpeakEngine.swift b/Sources/LiveSubs/SpeakEngine.swift
index b4e9df4..b65d385 100644
--- a/Sources/LiveSubs/SpeakEngine.swift
+++ b/Sources/LiveSubs/SpeakEngine.swift
@@ -466,6 +466,11 @@ final class SpeakEngine {
func outputDevice() -> OutputDevice? {
let all = AudioDevices.outputs()
+ // 会议室: the people are in the room, so the translation comes out of the Mac's speakers.
+ if settings.listensToRoom {
+ if let d = all.first(where: { $0.uid == settings.speakOutput }), !d.isVirtualMic { return d }
+ return AudioDevices.defaultOutput
+ }
if !settings.speakOutput.isEmpty, let d = all.first(where: { $0.uid == settings.speakOutput }) { return d }
return all.first(where: \.isVirtualMic)
}
diff --git a/Sources/LiveSubs/Views.swift b/Sources/LiveSubs/Views.swift
index 93776ea..a692e25 100644
--- a/Sources/LiveSubs/Views.swift
+++ b/Sources/LiveSubs/Views.swift
@@ -43,20 +43,22 @@ struct ChoiceRow: View {
let label: String
let value: String
var badge: String? = nil
+ /// 40pt instead of 44, for the menu bar panel where four rows sit one above the other.
+ var compact = false
/// Groups the menu separates; a header is its grey section title.
let sections: [(header: String?, options: [ChoiceOption])]
let onPick: (String) -> Void
- init(label: String, value: String, badge: String? = nil,
+ init(label: String, value: String, badge: String? = nil, compact: Bool = false,
sections: [(header: String?, options: [ChoiceOption])], onPick: @escaping (String) -> Void) {
- self.label = label; self.value = value; self.badge = badge
+ self.label = label; self.value = value; self.badge = badge; self.compact = compact
self.sections = sections.filter { !$0.options.isEmpty }
self.onPick = onPick
}
- init(label: String, value: String, badge: String? = nil,
+ init(label: String, value: String, badge: String? = nil, compact: Bool = false,
options: [ChoiceOption], onPick: @escaping (String) -> Void) {
- self.init(label: label, value: value, badge: badge, sections: [(nil, options)], onPick: onPick)
+ self.init(label: label, value: value, badge: badge, compact: compact, sections: [(nil, options)], onPick: onPick)
}
var body: some View {
@@ -86,7 +88,7 @@ struct ChoiceRow: View {
Image(systemName: "chevron.down").font(.system(size: 10, weight: .semibold)).foregroundStyle(Palette.tertiary)
}
.padding(.horizontal, 12)
- .frame(height: 44)
+ .frame(height: compact ? 40 : 44)
.background(RoundedRectangle(cornerRadius: 11).fill(Palette.ground))
.contentShape(Rectangle())
}
@@ -133,8 +135,26 @@ struct MenuPanelView: View {
}
}
+ /// The panel's natural height, measured; past what the screen can show it scrolls.
+ @State private var contentHeight: CGFloat = 0
+
+ /// A popover taller than the screen is cut off at the top (a small screen, the menu bar on it).
+ private var maxHeight: CGFloat { (NSScreen.main?.visibleFrame.height ?? 900) - 24 }
+
var body: some View {
- VStack(alignment: .leading, spacing: 16) {
+ let measured = panel.background(GeometryReader { g in
+ Color.clear.preference(key: PanelHeightKey.self, value: g.size.height)
+ })
+ .onPreferenceChange(PanelHeightKey.self) { contentHeight = $0 }
+ if contentHeight > maxHeight {
+ ScrollView { measured }.frame(width: 320, height: maxHeight).background(Color.white)
+ } else {
+ measured
+ }
+ }
+
+ private var panel: some View {
+ VStack(alignment: .leading, spacing: 14) {
HStack(spacing: 12) {
LogoTile(size: 34)
VStack(alignment: .leading, spacing: 3) {
@@ -168,21 +188,21 @@ struct MenuPanelView: View {
if model.running { LanguageNotice(model: model) }
if model.roomPrompt { roomPromptStrip }
- VStack(spacing: 8) {
- ChoiceRow(label: L("听到"), value: heardValue.0, badge: heardValue.1, sections: sourceSections) {
+ VStack(spacing: 6) {
+ ChoiceRow(label: L("听哪里"), value: settings.listensToRoom ? L("会议室") : L("电脑声音"),
+ compact: true, options: [("system", L("电脑声音(线上会议、视频)")), ("room", L("会议室(用麦克风听桌边的人)"))]) {
+ model.listenSourceSelection = $0
+ }
+ ChoiceRow(label: L("听到"), value: heardValue.0, badge: heardValue.1, compact: true, sections: sourceSections) {
model.sourceSelection = $0
}
ChoiceRow(label: L("翻译成"),
value: targetName(model.listen.resolvedTarget),
// "Follow system" leaves no room for the language name in the panel.
badge: settings.target == "system" ? (uiIsChinese ? L("跟随系统") : L("系统")) : nil,
- options: targetOptions) {
+ compact: true, options: targetOptions) {
model.targetSelection = $0
}
- ChoiceRow(label: L("内容"), value: subtitleOptions.first { $0.id == model.subtitles }?.title ?? L("原文 + 译文"),
- badge: model.meetingSubtitles != nil ? L("仅本场") : nil, options: subtitleOptions) {
- model.setSubtitles($0)
- }
}
Divider()
@@ -216,29 +236,95 @@ struct MenuPanelView: View {
}
HStack(spacing: 8) {
ForEach(DisplayTile.modes, id: \.self) { mode in
- DisplayTile(mode: mode, selected: settings.displayMode == mode) { model.setDisplayMode(mode) }
+ DisplayTile(mode: mode, selected: settings.displayMode == mode, caption: tileCaption(mode)) {
+ pickDisplay(mode)
+ }
}
}
- displayCard
+ .fixedSize(horizontal: false, vertical: true)
+ if settings.displayMode != "notes" || !model.ling.hasKey { displayCard }
}
UpdateBanner(updates: model.updates, model: model)
Divider()
- HStack {
- Button("会议记录") { model.openMainWindow?() }
- Spacer()
- Button("退出") { NSApp.terminate(nil) }
- }
- .buttonStyle(.plain)
- .font(.system(size: 13))
- .foregroundStyle(Palette.secondary)
+ footer
}
- .padding(18)
+ .padding(16)
.frame(width: 320)
.background(Color.white)
}
+
+ /// The panel's actions as three equal buttons, so they read as buttons rather than loose
+ /// grey words. No version line: an update shows its own strip above, and 设置 › 会议记录 checks.
+ private var footer: some View {
+ VStack(spacing: 8) {
+ HStack(spacing: 6) {
+ PanelAction(L("会议记录"), symbol: "doc.text") { model.openMainWindow?() }
+ PanelAction(L("导入文件…"), symbol: "square.and.arrow.down") { model.chooseImportFiles() }
+ PanelAction(L("退出"), symbol: "power", quiet: true) { NSApp.terminate(nil) }
+ }
+ }
+ }
+
+ /// The picked 实时纪要 tile is also the notes window's open/close switch, so the panel
+ /// needs no separate row for it.
+ private func pickDisplay(_ mode: String) {
+ if mode == "notes", settings.displayMode == "notes" {
+ model.notesShown ? model.hideNotesWindow() : model.openNotesWindow()
+ } else {
+ model.setDisplayMode(mode)
+ }
+ }
+
+ private func tileCaption(_ mode: String) -> String? {
+ guard mode == "notes", settings.displayMode == "notes" else { return nil }
+ return model.notesShown ? L("再点收起") : L("再点打开")
+ }
+}
+
+private struct PanelHeightKey: PreferenceKey {
+ static let defaultValue: CGFloat = 0
+ static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) }
+}
+
+extension MenuPanelView {
+ /// 在会议室里开会?: the Mac has played nothing for a minute. Asked once a meeting.
+ var roomPromptStrip: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("在会议室里开会?").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
+ Text("电脑里 1 分钟没放出声音").font(.system(size: 11)).foregroundStyle(Palette.secondary)
+ }
+ HStack(spacing: 8) {
+ SoftButton(L("改听会议室"), dark: true) { model.answerRoomPrompt(true) }
+ SoftButton(L("不是")) { model.answerRoomPrompt(false) }
+ Spacer(minLength: 0)
+ }
+ }
+ .padding(12).frame(maxWidth: .infinity, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: 11).fill(Palette.accentPale))
+ }
+}
+
+/// Under the panel's status: the file being transcribed in the background, if any.
+struct PanelImportLine: View {
+ @ObservedObject var importer: FileImporter
+ @ObservedObject var store: SessionStore
+
+ var body: some View {
+ if let job = importer.current {
+ let name = store.session(job.id)?.displayTitle ?? job.url.lastPathComponent
+ HStack(spacing: 6) {
+ ProgressView(value: importer.progress).progressViewStyle(.circular).controlSize(.mini).tint(Palette.ink)
+ .frame(width: 10, height: 10)
+ Text(importer.queue.isEmpty ? L("后台转写 \(name) · \(Int(importer.progress * 100))%")
+ : L("后台转写 \(name) · \(Int(importer.progress * 100))%,还有 \(importer.queue.count) 个"))
+ .font(.system(size: 12)).foregroundStyle(Palette.secondary).lineLimit(1).truncationMode(.middle)
+ }
+ }
+ }
}
extension MenuPanelView {
@@ -261,37 +347,10 @@ extension MenuPanelView {
.font(.system(size: 12)).foregroundStyle(Palette.secondary)
.fixedSize(horizontal: false, vertical: true)
default:
- HStack(spacing: 10) {
- VStack(alignment: .leading, spacing: 2) {
- Text(model.notesShown ? L("纪要窗口已打开") : L("纪要窗口已收起"))
- .font(.system(size: 12)).foregroundStyle(Palette.ink)
- if !model.ling.hasKey {
- Text("填入 API key 后可生成纪要;文字记录照常保存")
- .font(.system(size: 11)).foregroundStyle(Palette.secondary)
- .fixedSize(horizontal: false, vertical: true)
- }
- }
- Spacer(minLength: 4)
- SoftButton(model.notesShown ? L("收起") : L("打开"), dark: !model.notesShown, onGrey: true) {
- model.notesShown ? model.hideNotesWindow() : model.openNotesWindow()
- }
- }
- Divider()
- // Tinted while on: sharing the screen shows the notes too.
- HStack(spacing: 10) {
- VStack(alignment: .leading, spacing: 2) {
- Text("共享屏幕时让对方看到").font(.system(size: 12)).foregroundStyle(Palette.ink)
- if settings.notesCapturable {
- Text("对方现在能看到纪要窗口").font(.system(size: 11)).foregroundStyle(Palette.accentInk)
- }
- }
- Spacer(minLength: 4)
- Toggle("共享屏幕时让对方看到", isOn: Binding(get: { settings.notesCapturable }, set: { model.setNotesCapturable($0) }))
- .toggleStyle(.switch).controlSize(.mini).labelsHidden().tint(Palette.accent)
- }
- .padding(.horizontal, 6).padding(.vertical, 4)
- .background(RoundedRectangle(cornerRadius: 8).fill(settings.notesCapturable ? Palette.accentPale : .clear))
- .padding(.horizontal, -6)
+ // Shown only without a Ling key: the notes window itself opens and closes from the tile.
+ Text("填入 API key 后可生成纪要;文字记录照常保存")
+ .font(.system(size: 12)).foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
}
}
.padding(12)
@@ -334,6 +393,7 @@ extension MenuPanelView {
/// What the switch changes, on hover and in the one-time question.
private var speakMicLine: String {
+ if settings.listensToRoom { return L("译文从扬声器念出来") }
guard let mic = model.virtualMic?.name else { return L("先装好虚拟麦克风,对方才听得到") }
return settings.autoSystemMic ? L("系统麦克风换成 \(mic)") : L("译文送进 \(mic)")
}
@@ -368,7 +428,7 @@ extension MenuPanelView {
speakQuestion
} else if settings.speakEnabled {
talkCard
- if model.lastSpeakLatency == nil, model.virtualMic != nil, model.speakPhase == .idle {
+ if model.lastSpeakLatency == nil, model.virtualMic != nil, !settings.listensToRoom, model.speakPhase == .idle {
Button("先试一句 →") { model.openSettings(.speak); model.speakTestShown = true }
.buttonStyle(.plain).font(.system(size: 12)).foregroundStyle(Palette.secondary)
}
@@ -422,6 +482,8 @@ extension MenuPanelView {
if model.talkNeedsPermission {
return (L("按键还需要“输入监控”权限"), L("去允许"), model.allowTalkKey)
}
+ // In 会议室 the translation is read out loud: no virtual mic, no meeting app to set up.
+ if settings.listensToRoom { return nil }
if model.virtualMic == nil {
return (L("虚拟麦克风还没装好"), L("设置"), { model.openSettings(.speak) })
}
@@ -447,6 +509,7 @@ extension MenuPanelView {
let hearer = model.micUsers.first { $0.state == .virtualMic }?.name
let detail = phase == .listening ? L("松开后播出\(speakTarget)")
: live ? L("说\(speakFrom) → \(speakTarget)")
+ : settings.listensToRoom ? L("扬声器念出\(speakTarget)")
: hearer.map { L("对方听到 \(speakTarget) · \($0)") } ?? L("对方听到 \(speakTarget)")
return HStack(spacing: 12) {
TalkKeyCap(text: talkKeyName, pressed: phase == .listening, live: live)
@@ -504,6 +567,8 @@ struct DisplayTile: View {
static let modes = ["notes", "bar", "none"]
let mode: String
let selected: Bool
+ /// Under the picked tile's name: what clicking it again does.
+ var caption: String? = nil
let action: () -> Void
private var title: String {
@@ -522,9 +587,15 @@ struct DisplayTile: View {
.font(.system(size: 12, weight: selected ? .semibold : .regular))
.foregroundStyle(selected ? Palette.ink : Palette.secondary)
.lineLimit(1).minimumScaleFactor(0.8)
+ .fixedSize(horizontal: false, vertical: true)
+ if let caption {
+ Text(caption).font(.system(size: 10)).foregroundStyle(Palette.secondary)
+ .lineLimit(1).minimumScaleFactor(0.8).padding(.top, -4)
+ }
}
.padding(.top, 10).padding(.bottom, 8).padding(.horizontal, 4)
- .frame(maxWidth: .infinity)
+ // The row grows by the caption; every tile takes the row's height.
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
.background(RoundedRectangle(cornerRadius: 11).fill(selected ? Color.white : Palette.ground))
.overlay(RoundedRectangle(cornerRadius: 11).stroke(selected ? Palette.ink : .clear, lineWidth: 2))
.contentShape(Rectangle())
@@ -574,6 +645,35 @@ struct KeyCap: View {
}
}
+/// One of the panel's footer buttons: an icon over its name on a grey tile.
+struct PanelAction: View {
+ let title: String
+ let symbol: String
+ /// 退出: grey ink, it ends the app rather than opening something.
+ var quiet = false
+ let action: () -> Void
+ @State private var hover = false
+
+ init(_ title: String, symbol: String, quiet: Bool = false, action: @escaping () -> Void) {
+ self.title = title; self.symbol = symbol; self.quiet = quiet; self.action = action
+ }
+
+ var body: some View {
+ Button(action: action) {
+ VStack(spacing: 4) {
+ Image(systemName: symbol).font(.system(size: 14, weight: .medium))
+ Text(title).font(.system(size: 12, weight: .semibold)).lineLimit(1).minimumScaleFactor(0.8)
+ }
+ .foregroundStyle(quiet ? Palette.secondary : Palette.ink)
+ .frame(maxWidth: .infinity, minHeight: 52)
+ .background(RoundedRectangle(cornerRadius: 10).fill(hover ? Palette.line : Palette.ground))
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .onHover { hover = $0 }
+ }
+}
+
// MARK: - Main window
struct MainWindowView: View {
diff --git a/Tests/LiveSubsTests/RoomTests.swift b/Tests/LiveSubsTests/RoomTests.swift
new file mode 100644
index 0000000..96ca372
--- /dev/null
+++ b/Tests/LiveSubsTests/RoomTests.swift
@@ -0,0 +1,76 @@
+import Foundation
+import Testing
+@testable import LiveSubs
+
+@Suite struct RoomTests {
+ typealias In = RoomMicPlan.Input
+ let builtIn = In(uid: "builtin", builtIn: true)
+ let usb = In(uid: "usb")
+ let airpods = In(uid: "airpods", bluetooth: true)
+ let blackhole = In(uid: "blackhole", virtual: true)
+
+ @Test func keepsTheChosenMicrophone() {
+ #expect(RoomMicPlan.pick(defaultUID: "usb", inputs: [builtIn, usb, airpods]) == "usb")
+ #expect(RoomMicPlan.pick(defaultUID: "builtin", inputs: [builtIn, usb]) == "builtin")
+ }
+
+ @Test func skipsTheVirtualMicAndHeadsets() {
+ // 同声传译 makes BlackHole the default; AirPods hear the wearer, not the table.
+ #expect(RoomMicPlan.pick(defaultUID: "blackhole", inputs: [blackhole, airpods, builtIn]) == "builtin")
+ #expect(RoomMicPlan.pick(defaultUID: "airpods", inputs: [airpods, usb, builtIn]) == "builtin")
+ #expect(RoomMicPlan.pick(defaultUID: "airpods", inputs: [airpods, usb]) == "usb")
+ }
+
+ @Test func aHeadsetIsBetterThanNothing() {
+ #expect(RoomMicPlan.pick(defaultUID: "blackhole", inputs: [blackhole, airpods]) == "airpods")
+ #expect(RoomMicPlan.pick(defaultUID: nil, inputs: [blackhole]) == nil)
+ }
+
+ @Test func asksAboutTheRoomAfterAQuietMinute() {
+ #expect(!RoomPrompt.asks(room: false, listened: 30, voiced: 0))
+ #expect(RoomPrompt.asks(room: false, listened: 61, voiced: 0))
+ // Something played: it is an online meeting after all.
+ #expect(!RoomPrompt.asks(room: false, listened: 300, voiced: 5))
+ // Already listening to the room.
+ #expect(!RoomPrompt.asks(room: true, listened: 300, voiced: 0))
+ }
+
+ @Test func notDuringACallOrOnceAnswered() {
+ #expect(RoomPrompt.shows(silent: true, answered: false, inCall: false))
+ #expect(!RoomPrompt.shows(silent: true, answered: true, inCall: false))
+ #expect(!RoomPrompt.shows(silent: true, answered: false, inCall: true))
+ #expect(!RoomPrompt.shows(silent: false, answered: false, inCall: false))
+ }
+}
+
+@Suite struct VoiceGateTests {
+ @Test func theMacsOwnAudioKeepsTheFixedLine() {
+ var g = VoiceGate()
+ let quiet = g.voiced(0.005), loud = g.voiced(0.02)
+ #expect(!quiet)
+ #expect(loud)
+ }
+
+ @Test func aQuietRoomHearsAQuietVoice() {
+ // Room noise ~0.002, a voice across the table ~0.006: below -40 dBFS, still speech.
+ var g = VoiceGate(adaptive: true)
+ for i in 0..<120 { _ = g.voiced(i % 3 == 0 ? 0.002 : 0.006) }
+ #expect(g.threshold < 0.006)
+ let voice = g.voiced(0.006), noise = g.voiced(0.002)
+ #expect(voice)
+ #expect(!noise)
+ }
+
+ @Test func talkingOnAndOnKeepsTheRoomsFloor() {
+ // Half a minute of steady talk: every second has one short gap between words at the room's level.
+ var g = VoiceGate(adaptive: true)
+ for i in 0..<(30 * VoiceGate.blocksPerSecond) { _ = g.voiced(i % VoiceGate.blocksPerSecond == 0 ? 0.002 : 0.012) }
+ #expect(g.threshold < 0.005)
+ }
+
+ @Test func aNoisyRoomNeverGoesAboveTheFixedLine() {
+ var g = VoiceGate(adaptive: true)
+ for _ in 0..<120 { _ = g.voiced(0.02) }
+ #expect(g.threshold == VoiceGate.fixed)
+ }
+}
diff --git a/tools/README.md b/tools/README.md
index 88fed43..7c0d329 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -7,6 +7,7 @@
- `lsctl <命令>`:通过分布式通知 `com.wquguru.cicada.debug` 遥控 App。
- 开关字幕:`start` / `stop`
+ - 听哪里:`listenSource:<system|room>`(room 用麦克风听会议室,日志里 `room mic started: <设备>`,念译文时 `room mic muted` / `open`),`roomPrompt:<room|no>` 等于在“在会议室里开会?”里点“改听会议室”或“不是”(听电脑 60 秒没声音才出现,日志 `mac silent true`)
- 打开界面:`open`(主窗口)、`panel`(菜单栏面板)、`settings[:speak]`(设置,可指定栏目)
- 虚拟麦克风:`micTest` 试音(往虚拟麦克风播一句再听回来,结果写进日志),`micNext` 做清单里的下一步
- 会议软件的麦克风:`micUsers` 把每个读麦克风的进程和列表写进日志,`micGuide:<bundle id 或名字>` 打开怎么改,`micGuideRender:<bundle id>=<png>`