知了 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: restart Core Audio after installing the virtual mic, add a loopback sound test and a settings window
wquguru8f57d3a69106
diff --git a/AGENTS.md b/AGENTS.mdindex 37ea780..6d358d4 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -4,12 +4,12 @@ Live Subs is a macOS menu bar app that turns whatever the Mac is playing (stream## Scope (deliberately small)-- Three surfaces, nothing more: the **menu bar panel** (on/off, heard language, translate-to language, "我说话也翻译", subtitle bar display mode, meeting records, quit), the **subtitle bar** on screen, and the **main window** (meeting records + a small settings sheet). First launch shows a three-step **onboarding** window (permissions, try the sample video, speaking).+- Three surfaces, nothing more: the **menu bar panel** (on/off, heard language, translate-to language, "我说话也翻译", subtitle bar display mode, meeting records, quit), the **subtitle bar** on screen, the **main window** (meeting records) and a **settings window** (sidebar: 听 / 我说话也翻译 / 字幕条 / 会议记录). First launch shows a three-step **onboarding** window (permissions, try the sample video, speaking).- Listening: system audio (Core Audio process tap, our own process excluded) → spoken-language detection across installed on-device models → on-device transcription (`SpeechAnalyzer` / `SpeechTranscriber`) → translation (Google endpoint) → subtitle bar. Every confirmed sentence goes into the live meeting record.- Language detection compares confidence: the same 3–6 s clip after a pause is transcribed by every installed model; a winner needs confidence ≥ 0.6 and a 0.08 lead; the first detection or a 0.30 lead switches at once, otherwise two agreeing detections. After a switch the last 8 s are replayed into the new model.- "Follow system" translates into the first system language that differs from the source language.- Subtitle bar: shows only while someone talks (auto) or always; tucks into a dot after 2/4/8 s of quiet; fades to 15% and stays click-through while the pointer passes over it; editable after the pointer rests 0.6 s (drag to move, drag the corner to scale, double-click resets); ⌃⌥S hides/shows. Position, width and size are remembered per display.-- Speaking: hold ⌥ Space → microphone → one `SpeechAnalyzer` per press, finished with `finalizeAndFinishThroughEndOfInput` → translate into the room's language → system voice → the chosen output device (a virtual microphone). The virtual microphone is BlackHole 2ch, installed from the app: download the official notarized package, check its pinned SHA-256, run `installer` through the standard administrator prompt. We never bundle the GPL driver.+- Speaking: hold ⌥ Space → microphone → one `SpeechAnalyzer` per press, finished with `finalizeAndFinishThroughEndOfInput` → translate into the room's language → system voice → the chosen output device (a virtual microphone). The virtual microphone is BlackHole 2ch, installed from the app: download the official notarized package, check its pinned SHA-256, run `installer` and restart `coreaudiod` in one standard administrator prompt (the package only copies the driver and asks for a reboot; Core Audio loads a new HAL plug-in only when it restarts). Then a loopback sound test: speak a fixed English phrase into the device, record its input side, transcribe it (`LoopbackTest`). The checklist UI (`MicSetupCard`) is shared by onboarding step 3 and settings. We never bundle the GPL driver.- Meeting records: one folder per meeting, `session.json` + `system.m4a` (+ `mic.m4a`); empty meetings are dropped; export to Markdown, Word (`.docx` via `NSAttributedString`) and SRT. Speaker labels are only "对方" (system audio) and "你" (microphone): no diarization yet.- Nothing the user does needs the Terminal. When a feature request fits none of the above, push back before adding UI.@@ -23,7 +23,7 @@ Live Subs is a macOS menu bar app that turns whatever the Mac is playing (stream## Layout- `Package.swift`: SwiftPM, macOS 26+, Swift 5 language mode, no dependencies.-- `Sources/LiveSubs`: the app. Engine files are UI-free: `SystemAudioTap`, `AudioRouter` (resample, feed, ring buffer, recording), `LanguageDetector`, `ListenEngine`, `SpeakEngine` (also the Carbon `HotKey`), `Translator`, `VirtualMic`, `SessionStore` (+ exports). UI: `Overlay` (subtitle bar), `Views` (panel, main window, settings), `Onboarding` (+ sample player, brand mark), `AppModel` (wiring, status item, windows, debug control, `@main`). `DMGBackground` draws the installer background; `DevBuild` tells dev from release.+- `Sources/LiveSubs`: the app. Engine files are UI-free: `SystemAudioTap`, `AudioRouter` (resample, feed, ring buffer, recording), `LanguageDetector`, `ListenEngine`, `SpeakEngine` (also the Carbon `HotKey`), `Translator`, `VirtualMic`, `SessionStore` (+ exports). UI: `Overlay` (subtitle bar), `Views` (panel, main window), `SettingsWindow` (settings + the virtual mic checklist), `Onboarding` (+ sample player, brand mark), `AppModel` (wiring, status item, windows, debug control, `@main`). `DMGBackground` draws the installer background; `DevBuild` tells dev from release.- `Sources/LiveSubsIcon`: CLI that renders the icon set (`--dev` adds the DEV band).- `Resources/`: `Info.plist`, `sample/` (the 7 s onboarding clip, made by `scripts/make-sample.sh`), `dmg/DS_Store` (installer window layout).- `scripts/build.sh`: builds `build/LiveSubs.app`. Without `RELEASE=1` it is a **dev build**: "Live Subs Dev", bundle id `com.wquguru.cicada.dev`, `LiveSubsDev` = `branch @ commit[+]` in Info.plist; "DEV" beside the menu bar glyph, a DEV badge and the stamp in the panel, a DEV band on the icon, its own settings, permissions, `~/Library/Application Support/LiveSubs Dev` and log `/tmp/livesubs-dev-debug.log`. Both builds are signed ad hoc with a fixed designated requirement (the bundle id) so rebuilding keeps the system-audio and microphone permissions. Don't change the release bundle id `com.wquguru.cicada`: permissions are tied to it.@@ -40,7 +40,7 @@ scripts/package.sh # DMG + zip + checksums in build/scripts/make-sample.sh # regenerate the onboarding sample clip```-Debug control: dev builds always accept commands on the distributed notification `com.wquguru.cicada.debug` (release builds only with `defaults write com.wquguru.cicada debug -bool true`, which also logs transcript text). Send them with `tools/lsctl` (`start`, `stop`, `open`, `panel`, `onboarding:<step>`, `samplePlay`, `speakFile:<audio>`, `place:x,y,w,font`, `frame`, `overlayState`, `export:<dir>` …).+Debug control: dev builds always accept commands on the distributed notification `com.wquguru.cicada.debug` (release builds only with `defaults write com.wquguru.cicada debug -bool true`, which also logs transcript text). Send them with `tools/lsctl` (`start`, `stop`, `open`, `panel`, `onboarding:<step>`, `samplePlay`, `speakFile:<audio>`, `settings:<listen|speak|overlay|records>`, `micTest`, `micNext`, `place:x,y,w,font`, `frame`, `overlayState`, `export:<dir>` …).Release: `scripts/release.sh <x.y.z>` (clean `main`, a `## x.y.z — <today>` section in `CHANGELOG.md`) bumps `Resources/Info.plist`, commits, tags `v<x.y.z>` and pushes; `.github/workflows/release.yml` (runner `macos-26`) builds the tag, checks it matches Info.plist and publishes the DMG, zip and checksums with notes from `scripts/release_notes.sh`. `build.yml` runs on pull requests and on demand only: macOS minutes are expensive for a private repo.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6fbc56a..b7c3b0d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,12 @@One section per release, newest first. `scripts/release.sh` needs the section, dated today;the release workflow publishes it as the release notes.+## Unreleased++- Fixed: installing the virtual microphone looked like it failed ("系统还没识别到"). The package installed fine, but macOS only loads a new audio driver after its audio service restarts; the same password prompt now restarts it. If the driver is already there but not loaded, the app offers "让系统认出它" instead of reinstalling.+- New: a sound test for the virtual microphone: the app plays a sentence into it, listens back and shows what the room will hear.+- New: a settings window with a sidebar (听 / 我说话也翻译 / 字幕条 / 会议记录) replaces the settings sheet; the virtual microphone is set up from a three-step checklist there and in the first-run guide.+## 2.0.0 — 2026-11-01- New: spoken-language auto-detection across the installed on-device models; translation target follows the system language or a manual choice.diff --git a/README.md b/README.mdindex 8634b34..e9a7805 100644--- a/README.md+++ b/README.md@@ -58,7 +58,7 @@ Download **`LiveSubs-<version>-macOS-AppleSilicon.dmg`** from [Releases](https:/The app is ad-hoc signed (not notarized). On first launch macOS blocks it: open **System Settings › Privacy & Security** and click **Open Anyway**.-The first launch walks you through three steps: turn on **system audio recording** (and, optionally, the microphone), play the built-in sample to see subtitles appear, and — if you want to speak back — install the virtual microphone with one click (it asks for your password once).+The first launch walks you through three steps: turn on **system audio recording** (and, optionally, the microphone), play the built-in sample to see subtitles appear, and — if you want to speak back — install the virtual microphone with one click (it asks for your password once); a quick sound test then confirms the room will hear you.## Usagediff --git a/README.zh-CN.md b/README.zh-CN.mdindex 9762a9f..8c3c82f 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -66,7 +66,7 @@ Live Subs 听电脑里正在播放的声音,比如直播、视频、会议或1. 打开「听电脑里的声音」,麦克风可选;2. 播放内置的示例视频,看字幕出来;-3. 如果想让对方听到你的翻译,一键安装虚拟麦克风(只需要输一次电脑密码)。+3. 如果想让对方听到你的翻译,一键安装虚拟麦克风(只需要输一次电脑密码),装好后自动试音,确认对方听得到。## 使用diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftindex e39a09c..1835a21 100644--- a/Sources/LiveSubs/AppModel.swift+++ b/Sources/LiveSubs/AppModel.swift@@ -22,7 +22,7 @@ final class AppModel: ObservableObject {@Published var candidates: [Lang] = []@Published var outputs: [OutputDevice] = []@Published var speakPhase: SpeakEngine.Phase = .idle- @Published var showSettings = false+ @Published var settingsSection: SettingsSection = .speak@Published var systemAudioOK = false@Published var micStatus: AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .audio)@Published var liveSource = ""@@ -33,6 +33,7 @@ final class AppModel: ObservableObject {var openOnboarding: (() -> Void)?var openMainWindow: (() -> Void)?+ var openSettingsWindow: (() -> Void)?var showPanel: (() -> Void)?private var lineForSegment: [Int: String] = [:]@@ -56,6 +57,11 @@ final class AppModel: ObservableObject {self.store.setTranslation(lineID: line, text)}+ installer.speakThrough = { [weak self] text, lang, device in+ await self?.speak.speak(text, language: lang, device: device)+ }+ installer.onLoaded = { [weak self] in self?.virtualMicInstalled() }+speak.translate = { [weak self] text, from, to inawait self?.listen.translate(text, source: from, target: to)}@@ -156,13 +162,20 @@ final class AppModel: ObservableObject {}}+ func openSettings(_ section: SettingsSection? = nil) {+ if let section { settingsSection = section }+ openSettingsWindow?()+ }+func ensureListening() {if !listen.isRunning { start() }}func virtualMicInstalled() {refreshOutputs()- // Core Audio restarts during the install; reattach the system-audio tap.+ // Core Audio restarted to load the driver: device IDs changed, reattach the+ // system-audio tap and rebuild the voice output.+ speak.resetOutput()listen.reconnectAudio()objectWillChange.send()}@@ -321,7 +334,11 @@ final class AppModel: ObservableObject {case "step": onboardingStep = Int(arg) ?? 1case "samplePlay": ensureListening(); sample.play()case "micVerify": installer.install(verifyOnly: true)- case "settings": openMainWindow?(); showSettings = true+ case "settings":+ settingsSection = SettingsSection(rawValue: arg) ?? settingsSection+ openSettings(settingsSection)+ case "micTest": installer.runTest()+ case "micNext": installer.next()case "speakOn": enableSpeaking(true)case "speakOff": enableSpeaking(false)case "speakOut": speak.debugOutputURL = arg.isEmpty ? nil : URL(fileURLWithPath: arg)@@ -358,6 +375,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {private var deviceListener: AudioObjectPropertyListenerBlock?private var deviceWork: DispatchWorkItem?private var onboardingWindow: NSWindow?+ private var settingsWindow: NSWindow?private var pollTimer: Timer?private var runningObserver: Any?@@ -365,6 +383,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {NSApp.setActivationPolicy(.accessory)setupStatusItem()model.openMainWindow = { [weak self] in self?.showMainWindow() }+ model.openSettingsWindow = { [weak self] in self?.showSettingsWindow() }model.showPanel = { [weak self] in self?.togglePopover() }model.openOnboarding = { [weak self] in self?.showOnboarding() }runningObserver = model.$running.sink { [weak self] live in@@ -454,6 +473,27 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {NSApp.activate()}+ func showSettingsWindow() {+ popover.performClose(nil)+ if settingsWindow == nil {+ let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 720, height: 600),+ styleMask: [.titled, .closable, .fullSizeContentView],+ backing: .buffered, defer: false)+ w.title = "设置"+ w.titlebarAppearsTransparent = true+ w.titleVisibility = .hidden+ w.isReleasedWhenClosed = false+ w.delegate = self+ w.contentView = NSHostingView(rootView: SettingsView(model: model, settings: model.settings, installer: model.installer))+ w.center()+ settingsWindow = w+ }+ model.refreshOutputs()+ NSApp.setActivationPolicy(.regular)+ settingsWindow?.makeKeyAndOrderFront(nil)+ NSApp.activate()+ }+func showOnboarding() {popover.performClose(nil)if onboardingWindow == nil {@@ -485,7 +525,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {model.sample.stop()UserDefaults.standard.set(true, forKey: "onboarded")}- let otherOpen = [mainWindow, onboardingWindow].contains { $0 != nil && $0 != w && $0!.isVisible }+ let otherOpen = [mainWindow, onboardingWindow, settingsWindow].contains { $0 != nil && $0 != w && $0!.isVisible }if !otherOpen { NSApp.setActivationPolicy(.accessory) }}diff --git a/Sources/LiveSubs/Onboarding.swift b/Sources/LiveSubs/Onboarding.swiftindex 4d142c3..a977a29 100644--- a/Sources/LiveSubs/Onboarding.swift+++ b/Sources/LiveSubs/Onboarding.swift@@ -370,65 +370,30 @@ struct OnboardingView: View {}}VStack(spacing: 0) {- row(icon: "mic.badge.plus", tint: Palette.accentPale, iconColor: Palette.accentInk,- title: "虚拟麦克风", detail: micDetail) {- if model.virtualMic != nil {- done("已安装")- } else {- switch installer.state {- case .downloading: progressLabel("下载中…")- case .installing: progressLabel("安装中…")- default: primary("一键安装") { installer.install { model.virtualMicInstalled() } }- }- }- }+ MicSetupCard(installer: installer, deviceName: model.virtualMic?.name)+ .padding(.horizontal, 6).padding(.vertical, 4)Divider().padding(.horizontal, 22)HStack(spacing: 16) {- Text("按住说话").font(.system(size: 15, weight: .semibold))+ Text("按住说话").font(.system(size: 14, weight: .semibold))Spacer()Toggle("按住说话", isOn: Binding(get: { settings.speakEnabled }, set: { model.enableSpeaking($0) })).toggleStyle(.switch).labelsHidden().tint(Palette.ink)}- .padding(.horizontal, 22).padding(.vertical, 16)- Divider().padding(.horizontal, 22)- HStack(spacing: 16) {- Text("对方听到").font(.system(size: 15, weight: .semibold))- Spacer()- Picker("对方听到", selection: $settings.speakTo) {- Text("跟着对方说的语言").tag("room")- ForEach(targetLanguages, id: \.code) { Text($0.name).tag($0.code) }- }- .labelsHidden().frame(width: 200)- }.padding(.horizontal, 22).padding(.vertical, 14)}.background(RoundedRectangle(cornerRadius: 18).fill(Color.white)).overlay(RoundedRectangle(cornerRadius: 18).stroke(Palette.line, lineWidth: 1))- if model.virtualMic != nil {- (Text("在会议软件里,把麦克风选成 ") + Text(model.virtualMic?.name ?? "BlackHole 2ch").bold())+ if model.virtualMic != nil && installer.passed {+ (Text("最后一步:在会议软件里,把麦克风选成 ") + Text(model.virtualMic?.name ?? "BlackHole 2ch").bold()).font(.system(size: 13)).foregroundStyle(Palette.ink).padding(.horizontal, 16).padding(.vertical, 12).frame(maxWidth: .infinity, alignment: .leading).background(RoundedRectangle(cornerRadius: 12).fill(Palette.accentPale))- } else if case .failed(let msg) = installer.state {- Text(msg).font(.system(size: 13)).foregroundStyle(Palette.accentInk)}}}- private var micDetail: String {- if model.virtualMic != nil { return "已装好" }- return "需要输一次电脑密码"- }-- private func progressLabel(_ text: String) -> some View {- HStack(spacing: 8) {- ProgressView().controlSize(.small)- Text(text).font(.system(size: 12)).foregroundStyle(Palette.secondary)- }- }-private func key(_ top: String, _ bottom: String, width: CGFloat) -> some View {VStack(alignment: .leading) {Text(top).frame(maxWidth: .infinity, alignment: .trailing)diff --git a/Sources/LiveSubs/SettingsWindow.swift b/Sources/LiveSubs/SettingsWindow.swiftnew file mode 100644index 0000000..55e1d38--- /dev/null+++ b/Sources/LiveSubs/SettingsWindow.swift@@ -0,0 +1,389 @@+import AppKit+import SwiftUI++enum SettingsSection: String, CaseIterable, Identifiable {+ case listen, speak, overlay, records+ var id: String { rawValue }+ var title: String {+ switch self {+ case .listen: "听"+ case .speak: "我说话也翻译"+ case .overlay: "字幕条"+ case .records: "会议记录"+ }+ }+ var icon: String {+ switch self {+ case .listen: "waveform"+ case .speak: "mic"+ case .overlay: "captions.bubble"+ case .records: "doc.text"+ }+ }+}++// MARK: - Building blocks++/// A white card of rows separated by hairlines, like System Settings.+struct SettingsCard<Content: View>: View {+ @ViewBuilder var content: Content+ var body: some View {+ VStack(spacing: 0) { content }+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))+ }+}++struct SettingsRow<Trailing: View>: View {+ let title: String+ var detail: String? = nil+ var divider = true+ @ViewBuilder var trailing: Trailing+ var body: some View {+ VStack(spacing: 0) {+ HStack(spacing: 12) {+ VStack(alignment: .leading, spacing: 2) {+ Text(title).font(.system(size: 13)).foregroundStyle(Palette.ink)+ if let detail {+ Text(detail).font(.system(size: 11)).foregroundStyle(Palette.tertiary)+ }+ }+ Spacer(minLength: 12)+ trailing+ }+ .padding(.horizontal, 16)+ .frame(minHeight: 46)+ if divider { Divider().padding(.leading, 16) }+ }+ }+}++/// A grey pill that opens a menu: the value and a small chevron.+struct PillMenu: View {+ let value: String+ let options: [(id: String, title: String)]+ let onPick: (String) -> Void+ var body: some View {+ Menu {+ ForEach(options, id: \.id) { o in Button(o.title) { onPick(o.id) } }+ } label: {+ HStack(spacing: 6) {+ Text(value).font(.system(size: 13)).foregroundStyle(Palette.ink).lineLimit(1)+ Image(systemName: "chevron.up.chevron.down").font(.system(size: 9, weight: .semibold))+ .foregroundStyle(Palette.secondary)+ }+ .padding(.horizontal, 10).frame(height: 28)+ .background(RoundedRectangle(cornerRadius: 7).fill(Palette.ground))+ .contentShape(Rectangle())+ }+ .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()+ }+}++struct SoftButton: View {+ let title: String+ var dark = false+ let action: () -> Void+ init(_ title: String, dark: Bool = false, action: @escaping () -> Void) {+ self.title = title+ self.dark = dark+ self.action = action+ }+ var body: some View {+ Button(action: action) {+ Text(title).font(.system(size: 12, weight: .semibold))+ .foregroundStyle(dark ? Color.white : Palette.ink)+ .padding(.horizontal, 12).frame(height: 28)+ .background(RoundedRectangle(cornerRadius: 7).fill(dark ? Palette.ink : Color(white: 0.925)))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ }+}++// MARK: - Virtual microphone checklist++/// The one place the virtual mic is set up: onboarding step 3 and the settings window.+/// Not ready → a three-step checklist with one button that does the next step.+/// Ready → one line with a status dot and the sound test.+struct MicSetupCard: View {+ @ObservedObject var installer: VirtualMicInstaller+ /// Re-read the device list when the app's copy changes.+ var deviceName: String?++ private var onDisk: Bool { installer.isOnDisk || deviceName != nil }+ private var loaded: Bool { deviceName != nil }++ var body: some View {+ if loaded && installer.passed && installer.state != .testing {+ ready+ } else {+ checklist+ }+ }++ private var ready: some View {+ VStack(alignment: .leading, spacing: 12) {+ HStack(spacing: 12) {+ Circle().fill(Color(red: 0.12, green: 0.62, blue: 0.33)).frame(width: 9, height: 9)+ VStack(alignment: .leading, spacing: 2) {+ Text("虚拟麦克风已就绪").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)+ Text("\(deviceName ?? "BlackHole 2ch") · 试音通过,对方听得到").font(.system(size: 11)).foregroundStyle(Palette.tertiary)+ }+ Spacer()+ SoftButton("再试一次") { installer.runTest() }+ }+ if let t = installer.test { TestResultView(result: t) }+ }+ .padding(16)+ }++ private var checklist: some View {+ VStack(alignment: .leading, spacing: 14) {+ HStack {+ Text("虚拟麦克风").font(.system(size: 14, weight: .semibold)).foregroundStyle(Palette.ink)+ Spacer()+ Text(statusTag).font(.system(size: 11, weight: .semibold))+ .foregroundStyle(installer.busy ? Palette.accentInk : Palette.tertiary)+ }+ step(1, "安装", "输一次电脑密码", done: onDisk,+ active: installer.state == .downloading || installer.state == .installing,+ activeText: installer.state == .downloading ? "正在下载…" : "正在安装…")+ step(2, "让系统认出它", "声音会断一下,约 1 秒", done: loaded,+ active: installer.state == .reloading, activeText: "正在让系统认出它…")+ step(3, "试音", "自动播一句,确认对方听得到", done: installer.passed,+ active: installer.state == .testing, activeText: "正在试音…")+ if let t = installer.test, !t.heard, installer.state != .testing {+ TestResultView(result: t)+ }+ if case .failed(let msg) = installer.state {+ Text(msg).font(.system(size: 12)).foregroundStyle(Palette.accentInk)+ }+ if !installer.busy {+ SoftButton(buttonTitle, dark: true) { installer.next() }+ }+ }+ .padding(16)+ }++ private var statusTag: String {+ if installer.busy { return "进行中" }+ if !onDisk { return "没装" }+ if !loaded { return "系统还没认出" }+ return installer.test == nil ? "还没试音" : "没听到声音"+ }++ private var buttonTitle: String {+ if !onDisk { return "一键安装" }+ if !loaded { return "让系统认出它" }+ return installer.test == nil ? "试音" : "再试一次"+ }++ private func step(_ n: Int, _ title: String, _ detail: String, done: Bool, active: Bool, activeText: String) -> some View {+ HStack(alignment: .top, spacing: 12) {+ ZStack {+ Circle().fill(done ? Palette.ink : active ? Palette.accentPale : Palette.ground)+ if done {+ Image(systemName: "checkmark").font(.system(size: 10, weight: .bold)).foregroundStyle(.white)+ } else if active {+ ProgressView().controlSize(.mini)+ } else {+ Text("\(n)").font(.system(size: 11, weight: .bold)).foregroundStyle(Palette.secondary)+ }+ }+ .frame(width: 22, height: 22)+ VStack(alignment: .leading, spacing: 2) {+ Text(active ? activeText : title).font(.system(size: 13, weight: .semibold))+ .foregroundStyle(done || active ? Palette.ink : Palette.secondary)+ if !done && !active {+ Text(detail).font(.system(size: 11)).foregroundStyle(Palette.tertiary)+ }+ }+ .padding(.top, 2)+ }+ }+}++struct TestResultView: View {+ let result: VirtualMicInstaller.TestResult+ var body: some View {+ HStack(alignment: .center, spacing: 12) {+ HStack(alignment: .center, spacing: 2) {+ ForEach(Array(result.levels.enumerated()), id: \.offset) { _, l in+ Capsule().fill(result.heard ? Palette.accent : Color(white: 0.8))+ .frame(width: 3, height: max(3, CGFloat(min(1, l * 2.5)) * 24))+ }+ }+ .frame(height: 24)+ if result.heard {+ (Text("对方会听到:") + Text(result.text.isEmpty ? "一段声音" : "“\(result.text)”").bold())+ .font(.system(size: 12)).foregroundStyle(Palette.ink)+ } else {+ Text("虚拟麦克风里没收到声音,再试一次").font(.system(size: 12)).foregroundStyle(Palette.accentInk)+ }+ Spacer(minLength: 0)+ }+ .padding(.horizontal, 12).padding(.vertical, 8)+ .background(RoundedRectangle(cornerRadius: 9).fill(result.heard ? Palette.ground : Palette.accentPale))+ }+}++// MARK: - Settings window++struct SettingsView: View {+ @ObservedObject var model: AppModel+ @ObservedObject var settings: AppSettings+ @ObservedObject var installer: VirtualMicInstaller++ var body: some View {+ HStack(spacing: 0) {+ sidebar.frame(width: 190)+ ScrollView {+ VStack(alignment: .leading, spacing: 16) {+ Text(model.settingsSection.title).font(.system(size: 20, weight: .bold)).foregroundStyle(Palette.ink)+ switch model.settingsSection {+ case .listen: listen+ case .speak: speak+ case .overlay: overlay+ case .records: records+ }+ }+ .padding(.leading, 12).padding(.trailing, 28).padding(.top, 40).padding(.bottom, 28)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ }+ .frame(width: 720, height: 600)+ .background(Color(red: 0.965, green: 0.969, blue: 0.976))+ }++ private var sidebar: some View {+ VStack(alignment: .leading, spacing: 2) {+ ForEach(SettingsSection.allCases) { s in+ let on = s == model.settingsSection+ Button { model.settingsSection = s } label: {+ HStack(spacing: 10) {+ Image(systemName: s.icon).font(.system(size: 13))+ .foregroundStyle(on ? Palette.accent : Palette.secondary).frame(width: 18)+ Text(s.title).font(.system(size: 13, weight: on ? .semibold : .regular)).foregroundStyle(Palette.ink)+ Spacer()+ if s == .speak && settings.speakEnabled && model.virtualMic == nil {+ Circle().fill(Palette.accent).frame(width: 6, height: 6)+ }+ }+ .padding(.horizontal, 10).frame(height: 32)+ .background(RoundedRectangle(cornerRadius: 8).fill(on ? Color.white : .clear))+ .overlay(RoundedRectangle(cornerRadius: 8).stroke(on ? Palette.line : .clear, lineWidth: 1))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ }+ Spacer()+ }+ .padding(.horizontal, 10).padding(.top, 44).padding(.bottom, 14)+ }++ // MARK: Sections++ private var listen: some View {+ SettingsCard {+ SettingsRow(title: "听到") {+ PillMenu(value: heardValue, options: [("auto", "自动识别")] + sourceLanguages.map { ($0.locale, $0.name) }) {+ model.sourceSelection = $0+ }+ }+ SettingsRow(title: "翻译成", divider: false) {+ PillMenu(value: settings.target == "system" ? "跟随系统(\(targetName(model.listen.resolvedTarget)))"+ : targetName(settings.target),+ options: [("system", "跟随系统")] + targetLanguages.map { ($0.code, $0.name) }) {+ model.targetSelection = $0+ }+ }+ }+ }++ private var heardValue: String {+ if case .fixed(let l) = settings.sourceMode { return l.name }+ return "自动识别"+ }++ private var speak: some View {+ VStack(alignment: .leading, spacing: 14) {+ SettingsCard { MicSetupCard(installer: installer, deviceName: model.virtualMic?.name) }+ SettingsCard {+ SettingsRow(title: "我说话也翻译") {+ Toggle("我说话也翻译", isOn: Binding(get: { settings.speakEnabled }, set: { model.enableSpeaking($0) }))+ .toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)+ }+ SettingsRow(title: "按住说话") { KeyCap(HotKey.display) }+ SettingsRow(title: "我说的语言") {+ PillMenu(value: settings.speakFromLang.name, options: sourceLanguages.map { ($0.locale, $0.name) }) {+ settings.speakFrom = $0+ model.speakFromChanged()+ }+ }+ SettingsRow(title: "对方听到") {+ PillMenu(value: settings.speakTo == "room" ? "跟随对方的语言" : targetName(settings.speakTo),+ options: [("room", "跟随对方的语言")] + targetLanguages.map { ($0.code, $0.name) }) {+ settings.speakTo = $0+ }+ }+ SettingsRow(title: "声音送到", divider: false) {+ PillMenu(value: outputName,+ options: [("", "虚拟麦克风(自动)")] + model.outputs.map { ($0.uid, $0.name) }) {+ settings.speakOutput = $0+ }+ }+ }+ Text("在会议软件里,把麦克风选成「\(model.virtualMic?.name ?? "BlackHole 2ch")」。")+ .font(.system(size: 12)).foregroundStyle(Palette.secondary).padding(.horizontal, 4)+ }+ }++ private var outputName: String {+ if settings.speakOutput.isEmpty { return "虚拟麦克风(自动)" }+ return model.outputs.first { $0.uid == settings.speakOutput }?.name ?? "虚拟麦克风(自动)"+ }++ private var overlay: some View {+ VStack(alignment: .leading, spacing: 14) {+ SettingsCard {+ SettingsRow(title: "显示") {+ Picker("显示", selection: Binding(get: { settings.overlayAuto }, set: { model.setOverlayAuto($0) })) {+ Text("说话时").tag(true)+ Text("一直").tag(false)+ }+ .pickerStyle(.segmented).labelsHidden().frame(width: 140)+ }+ if settings.overlayAuto {+ SettingsRow(title: "安静多久后收起") {+ Picker("收起", selection: $settings.overlayHideAfter) {+ Text("2 秒").tag(2.0)+ Text("4 秒").tag(4.0)+ Text("8 秒").tag(8.0)+ }+ .pickerStyle(.segmented).labelsHidden().frame(width: 140)+ }+ }+ SettingsRow(title: "随时显示 / 隐藏") { KeyCap("⌃ ⌥ S") }+ SettingsRow(title: "位置和大小", detail: "鼠标停住不动可拖动,拖右下角缩放", divider: false) {+ SoftButton("恢复默认") { model.overlay.resetPosition() }+ }+ }+ }+ }++ private var records: some View {+ SettingsCard {+ SettingsRow(title: "保存会议录音", detail: "只存在这台 Mac 上") {+ Toggle("保存会议录音", isOn: $settings.recordAudio)+ .toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)+ }+ SettingsRow(title: "记录文件夹") {+ SoftButton("打开") { NSWorkspace.shared.open(model.store.root) }+ }+ SettingsRow(title: "首次引导", divider: false) {+ SoftButton("重新看") { model.onboardingStep = 1; model.openOnboarding?() }+ }+ }+ }+}diff --git a/Sources/LiveSubs/SpeakEngine.swift b/Sources/LiveSubs/SpeakEngine.swiftindex 90783d4..97c8a1a 100644--- a/Sources/LiveSubs/SpeakEngine.swift+++ b/Sources/LiveSubs/SpeakEngine.swift@@ -392,13 +392,14 @@ final class SpeakEngine {}}- func speak(_ text: String, language: String) async {+ /// `device` overrides the chosen output (the virtual mic sound test).+ func speak(_ text: String, language: String, device override: OutputDevice? = nil) async {let buffers = await synthesize(text, language: language)guard let first = buffers.first else { return }if let url = debugOutputURL, let f = AudioFileWriter.open(url, format: first.format) {for b in buffers { try? f.write(from: b) }}- let device = outputDevice()+ let device = override ?? outputDevice()configureOutput(format: first.format, device: device)do {if !out.isRunning { try out.start() }@@ -419,6 +420,14 @@ final class SpeakEngine {debugLog("spoke \(buffers.count) buffers to \(device?.name ?? "default output")")}+ /// Core Audio restarted (virtual mic install): device IDs changed, rebuild the output next time.+ func resetOutput() {+ player.stop()+ out.stop()+ outFormat = nil+ outDeviceUID = nil+ }+private func configureOutput(format: AVAudioFormat, device: OutputDevice?) {let uid = device?.uid ?? ""guard outFormat != format || outDeviceUID != uid else { return }diff --git a/Sources/LiveSubs/Views.swift b/Sources/LiveSubs/Views.swiftindex 127a8ae..20701ab 100644--- a/Sources/LiveSubs/Views.swift+++ b/Sources/LiveSubs/Views.swift@@ -138,10 +138,9 @@ struct MenuPanelView: View {}if settings.speakEnabled && model.virtualMic == nil {HStack {- Text("还没有虚拟麦克风,对方听不到").font(.system(size: 12)).foregroundStyle(Palette.accentInk)+ Text("虚拟麦克风还没设置好,对方听不到").font(.system(size: 12)).foregroundStyle(Palette.accentInk)Spacer()- InstallMicButton(installer: model.installer) { model.virtualMicInstalled() }- .font(.system(size: 12))+ SoftButton("设置") { model.openSettings(.speak) }}.padding(10).frame(maxWidth: .infinity, alignment: .leading).background(RoundedRectangle(cornerRadius: 9).fill(Palette.accentPale))@@ -241,9 +240,6 @@ struct MainWindowView: View {.padding(.trailing, 14).padding(.bottom, 14).padding(.top, 38)}.background(Palette.ground)- .sheet(isPresented: $model.showSettings) {- SettingsSheet(model: model, settings: settings)- }}// MARK: Sidebar@@ -254,7 +250,7 @@ struct MainWindowView: View {LogoTile(size: 28)Text("会议记录").font(.system(size: 15, weight: .bold)).foregroundStyle(Palette.ink)Spacer()- Button { model.showSettings = true } label: {+ Button { model.openSettings() } label: {Image(systemName: "slider.horizontal.3").font(.system(size: 14)).frame(width: 32, height: 32)}.buttonStyle(.plain).foregroundStyle(Palette.secondary).help("设置")@@ -437,95 +433,3 @@ struct MainWindowView: View {.padding(.vertical, 12)}}--// MARK: - Settings sheet--struct SettingsSheet: View {- @ObservedObject var model: AppModel- @ObservedObject var settings: AppSettings- @Environment(\.dismiss) private var dismiss-- var body: some View {- VStack(alignment: .leading, spacing: 18) {- Text("设置").font(.system(size: 18, weight: .bold))-- group("会议记录") {- Toggle("保存会议录音(只存在这台 Mac 上)", isOn: $settings.recordAudio)- Button("打开记录文件夹") { NSWorkspace.shared.open(model.store.root) }- }-- group("我说话也翻译") {- Picker("我说的语言", selection: Binding(get: { settings.speakFrom },- set: { settings.speakFrom = $0; model.speakFromChanged() })) {- ForEach(sourceLanguages, id: \.locale) { Text($0.name).tag($0.locale) }- }- Picker("对方听到", selection: $settings.speakTo) {- Text("跟随房间语言").tag("room")- ForEach(targetLanguages, id: \.code) { Text($0.name).tag($0.code) }- }- Picker("声音输出到", selection: $settings.speakOutput) {- Text("自动(优先虚拟麦克风)").tag("")- ForEach(model.outputs) { Text($0.name).tag($0.uid) }- }- HStack {- Text("按住").foregroundStyle(Palette.secondary)- KeyCap(HotKey.display)- Text("说话,松开后发送译文").foregroundStyle(Palette.secondary)- Spacer()- Button("试听") { model.speak.preview() }- }- .font(.system(size: 12))- if model.virtualMic == nil {- HStack {- Text("让对方听到译文,需要虚拟麦克风")- .font(.system(size: 12)).foregroundStyle(Palette.accentInk)- Spacer()- InstallMicButton(installer: model.installer) { model.virtualMicInstalled() }- }- } else {- Text("在会议软件里,把麦克风选成 \(model.virtualMic?.name ?? "")")- .font(.system(size: 12)).foregroundStyle(Palette.secondary)- }- }-- group("字幕条") {- Text("说话时自动出现,安静后收成小点;鼠标经过会变透明。停住不动 0.6 秒可拖动,拖右下角缩放,双击回到默认位置。⌃⌥S 随时显示 / 隐藏。")- .font(.system(size: 12)).foregroundStyle(Palette.secondary)- HStack {- Button("恢复默认位置") { model.overlay.resetPosition() }- Button("重新看引导") { dismiss(); model.onboardingStep = 1; model.openOnboarding?() }- }- }-- HStack {- Spacer()- Button("完成") { dismiss() }.keyboardShortcut(.defaultAction)- }- }- .padding(24)- .frame(width: 460)- }-- private func group<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {- VStack(alignment: .leading, spacing: 10) {- Text(title).font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.secondary)- VStack(alignment: .leading, spacing: 10) { content() }- .padding(14)- .frame(maxWidth: .infinity, alignment: .leading)- .background(RoundedRectangle(cornerRadius: 12).fill(Palette.ground))- }- }-}--struct InstallMicButton: View {- @ObservedObject var installer: VirtualMicInstaller- var onInstalled: () -> Void- var body: some View {- switch installer.state {- case .downloading, .installing:- HStack(spacing: 6) { ProgressView().controlSize(.small); Text(installer.state == .downloading ? "下载中…" : "安装中…").font(.system(size: 12)) }- default:- Button("一键安装") { installer.install(onInstalled: onInstalled) }- }- }-}diff --git a/Sources/LiveSubs/VirtualMic.swift b/Sources/LiveSubs/VirtualMic.swiftindex d1ceb0e..e13d96b 100644--- a/Sources/LiveSubs/VirtualMic.swift+++ b/Sources/LiveSubs/VirtualMic.swift@@ -1,92 +1,270 @@import AppKit+import AVFoundation+import CoreAudioimport CryptoKitimport Foundation+import Speech-/// Installs the BlackHole 2ch virtual audio device without the Terminal:-/// download the official, Apple-notarized installer, verify its SHA-256,-/// then run it through the standard macOS administrator password dialog.-/// (We download it rather than bundling it, so we don't redistribute the GPL driver.)+/// Sets up the BlackHole 2ch virtual microphone without the Terminal, in three steps the UI+/// shows as a checklist: install → let the system load it → sound test.+///+/// Install: download the official, Apple-notarized package, verify its SHA-256, run it through+/// the standard administrator prompt. (Downloaded, not bundled: we don't redistribute the GPL+/// driver.) The package only copies the driver and asks for a reboot; Core Audio doesn't load a+/// new HAL plug-in until `coreaudiod` restarts, so the same prompt restarts it.+///+/// Test: speak a phrase into the virtual mic and listen back from its input side, so we know the+/// whole path the meeting app will use works — not just that a device with the name exists.@MainActorfinal class VirtualMicInstaller: ObservableObject {enum State: Equatable {case idlecase downloadingcase installing- case done+ case reloading+ case testingcase failed(String)}+ struct TestResult: Equatable {+ var heard: Bool+ var text: String+ var levels: [Float]+ }+@Published private(set) var state: State = .idle+ @Published private(set) var test: TestResult?+ /// Bumped after Core Audio restarts so views re-read the device list.+ @Published private(set) var generation = 0static let packageURL = URL(string: "https://existential.audio/downloads/BlackHole2ch-0.7.1.pkg")!static let packageSHA256 = "57b540f27a3e29c37e310e01bee0fdfab76733087e47f997ef9dccf851400dcf"+ static let driverPath = "/Library/Audio/Plug-Ins/HAL/BlackHole2ch.driver"+ static let testPhrase = "Hi, can you hear me?"++ /// Plays text through a given device; provided by the speak engine.+ var speakThrough: ((_ text: String, _ language: String, _ device: OutputDevice) async -> Void)?+ /// Called once Core Audio has the device (after an install or reload).+ var onLoaded: (() -> Void)?++ var device: OutputDevice? { AudioDevices.virtualMic }+ var isLoaded: Bool { device != nil }+ /// Installed on disk; may not be loaded until Core Audio restarts.+ var isOnDisk: Bool { FileManager.default.fileExists(atPath: Self.driverPath) }+ var busy: Bool { [.downloading, .installing, .reloading, .testing].contains(state) }+ var passed: Bool { test?.heard == true }- var isInstalled: Bool { AudioDevices.virtualMic != nil }+ // Kept for existing callers.+ var isInstalled: Bool { isLoaded }++ /// The next thing to do, whatever state the Mac is in.+ func next() {+ if !isOnDisk && !isLoaded { install() } else if !isLoaded { reload() } else { runTest() }+ }/// `verifyOnly` stops after the download and checksum (used by tests).func install(verifyOnly: Bool = false, onInstalled: (() -> Void)? = nil) {- guard state != .downloading && state != .installing else { return }- Task { await run(verifyOnly: verifyOnly, onInstalled: onInstalled) }+ guard !busy else { return }+ Task {+ guard let pkg = await download() else { return }+ if verifyOnly { state = .idle; return }+ state = .installing+ try? await Task.sleep(nanoseconds: 200_000_000) // let "安装中" show before the dialog+ let cmd = "/usr/sbin/installer -pkg " + shellQuote(pkg.path) + " -target / && " + Self.restartAudio+ guard runPrivileged(cmd, prompt: "Live Subs 要安装虚拟麦克风,让会议里的人听到你的翻译。") else { return }+ state = .reloading+ await waitForDevice(onLoaded: onInstalled)+ }}- private func run(verifyOnly: Bool, onInstalled: (() -> Void)?) async {+ /// The driver is on disk but Core Audio hasn't loaded it: restart Core Audio only.+ func reload() {+ guard !busy else { return }+ Task {+ state = .reloading+ try? await Task.sleep(nanoseconds: 200_000_000)+ guard runPrivileged(Self.restartAudio, prompt: "Live Subs 要让系统认出虚拟麦克风,声音会断约 1 秒。") else { return }+ await waitForDevice(onLoaded: nil)+ }+ }++ func runTest() {+ guard !busy, let device else { return }+ Task {+ state = .testing+ test = await LoopbackTest.run(device: device, phrase: Self.testPhrase) { [weak self] in+ await self?.speakThrough?(Self.testPhrase, "en", device)+ }+ debugLog("virtual mic test: heard=\(test?.heard ?? false) text=\(test?.text ?? "")")+ state = .idle+ }+ }++ // MARK: Steps++ // `launchctl kickstart` is the supported restart; killall is the fallback (launchd relaunches it).+ private static let restartAudio =+ "/bin/launchctl kickstart -k system/com.apple.audio.coreaudiod || /usr/bin/killall coreaudiod"++ private func download() async -> URL? {state = .downloading- let pkg: URLdo {let (tmp, response) = try await URLSession.shared.download(from: Self.packageURL)guard (response as? HTTPURLResponse)?.statusCode == 200 else {state = .failed("下载失败,请检查网络")- return+ return nil}- let data = try Data(contentsOf: tmp)- let digest = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ let digest = SHA256.hash(data: try Data(contentsOf: tmp)).map { String(format: "%02x", $0) }.joined()guard digest == Self.packageSHA256 else {debugLog("virtual mic: checksum mismatch \(digest)")state = .failed("安装包校验没通过,已停止")- return+ return nil}let dir = FileManager.default.temporaryDirectory.appendingPathComponent("LiveSubsMic", isDirectory: true)try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)- pkg = dir.appendingPathComponent("BlackHole2ch.pkg")+ let pkg = dir.appendingPathComponent("BlackHole2ch.pkg")try? FileManager.default.removeItem(at: pkg)try FileManager.default.moveItem(at: tmp, to: pkg)debugLog("virtual mic: downloaded and verified \(pkg.path)")+ return pkg} catch {debugLog("virtual mic: download error \(error)")state = .failed("下载失败,请检查网络")- return- }- if verifyOnly {- state = .idle- return+ return nil}+ }- state = .installing- // Give the UI a beat to show "安装中" before the system dialog appears.- try? await Task.sleep(nanoseconds: 200_000_000)- let script = """- do shell script "/usr/sbin/installer -pkg " & quoted form of "\(pkg.path)" & " -target /" \- with prompt "Live Subs 要安装虚拟麦克风,让会议里的人听到你的翻译。" with administrator privileges- """+ /// Runs a shell command through the standard administrator prompt. Cancel goes back to idle.+ private func runPrivileged(_ command: String, prompt: String) -> Bool {+ let script = "do shell script \(appleQuote(command)) with prompt \(appleQuote(prompt)) with administrator privileges"var errorInfo: NSDictionary?NSAppleScript(source: script)?.executeAndReturnError(&errorInfo)- if let errorInfo {- let code = errorInfo[NSAppleScript.errorNumber] as? Int ?? 0- debugLog("virtual mic: installer error \(errorInfo)")- state = code == -128 ? .idle : .failed("安装没有完成,可以再试一次")+ guard let errorInfo else { return true }+ let code = errorInfo[NSAppleScript.errorNumber] as? Int ?? 0+ debugLog("virtual mic: privileged command error \(errorInfo)")+ state = code == -128 ? .idle : .failed("没有完成,可以再试一次")+ return false+ }++ private func waitForDevice(onLoaded extra: (() -> Void)?) async {+ for _ in 0..<30 where !isLoaded {+ try? await Task.sleep(nanoseconds: 500_000_000)+ }+ generation += 1+ guard isLoaded else {+ state = .failed(isOnDisk ? "系统还没认出它,点“让系统认出它”再试一次" : "安装没有完成,可以再试一次")return}- // Core Audio picks the new device up after a moment.- for _ in 0..<20 {- if isInstalled { break }- try? await Task.sleep(nanoseconds: 500_000_000)+ debugLog("virtual mic: loaded")+ state = .idle+ onLoaded?()+ extra?()+ // Core Audio just restarted; give it a moment before the test.+ try? await Task.sleep(nanoseconds: 800_000_000)+ runTest()+ }++ private func shellQuote(_ s: String) -> String { "'" + s.replacingOccurrences(of: "'", with: "'\\''") + "'" }+ private func appleQuote(_ s: String) -> String {+ "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""+ }+}++// MARK: - Loopback test++/// Records the virtual mic's input side while a phrase is played into its output side, then+/// transcribes the recording. Hearing the phrase back proves the room will hear us.+enum LoopbackTest {+ @MainActor+ static func run(device: OutputDevice, phrase: String, play: @escaping () async -> Void) async -> VirtualMicInstaller.TestResult {+ let recorder = LoopbackRecorder()+ guard recorder.start(deviceID: device.id) else {+ return .init(heard: false, text: "", levels: [])+ }+ try? await Task.sleep(nanoseconds: 150_000_000)+ await play()+ try? await Task.sleep(nanoseconds: 400_000_000)+ let buffers = recorder.stop()+ let levels = LoopbackRecorder.levels(buffers, bars: 12)+ let loud = (levels.max() ?? 0) > 0.02+ let text = loud ? await transcribe(buffers, locale: "en-US") : ""+ // Any real signal counts; the transcript is shown so people can judge it themselves.+ return .init(heard: loud, text: text, levels: levels)+ }++ private static func transcribe(_ buffers: [AVAudioPCMBuffer], locale: String) async -> String {+ let t = SpeechTranscriber(locale: Locale(identifier: locale), transcriptionOptions: [],+ reportingOptions: [], attributeOptions: [])+ guard await AssetInventory.status(forModules: [t]) == .installed,+ let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [t]) else { return "" }+ let (stream, cont) = AsyncStream.makeStream(of: AnalyzerInput.self)+ let conv = PCMConverter()+ for b in buffers { if let c = conv.convert(b, to: format) { cont.yield(AnalyzerInput(buffer: c)) } }+ cont.finish()+ let collector = Task { () -> String in+ var parts: [String] = []+ do {+ for try await r in t.results where r.isFinal {+ parts.append(String(r.text.characters).trimmingCharacters(in: .whitespaces))+ }+ } catch {}+ return parts.joined(separator: " ")+ }+ let analyzer = SpeechAnalyzer(inputSequence: stream, modules: [t])+ try? await analyzer.finalizeAndFinishThroughEndOfInput()+ return await collector.value+ }+}++/// An input-only engine pointed at one device (the virtual mic), collecting buffers.+final class LoopbackRecorder: @unchecked Sendable {+ private let engine = AVAudioEngine()+ private let lock = NSLock()+ private var buffers: [AVAudioPCMBuffer] = []++ func start(deviceID: AudioObjectID) -> Bool {+ let input = engine.inputNode+ guard let unit = input.audioUnit else { return false }+ var id = deviceID+ let status = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0,+ &id, UInt32(MemoryLayout<AudioObjectID>.size))+ let format = input.outputFormat(forBus: 0)+ guard status == noErr, format.sampleRate > 0 else {+ debugLog("loopback: cannot open device \(deviceID) status=\(status)")+ return false+ }+ input.installTap(onBus: 0, bufferSize: 4096, format: format) { [weak self] buf, _ in+ guard let self, let copy = buf.copy() as? AVAudioPCMBuffer else { return }+ self.lock.lock(); self.buffers.append(copy); self.lock.unlock()+ }+ do {+ try engine.start()+ return true+ } catch {+ debugLog("loopback: start failed \(error)")+ return false+ }+ }++ func stop() -> [AVAudioPCMBuffer] {+ engine.inputNode.removeTap(onBus: 0)+ engine.stop()+ lock.lock(); defer { lock.unlock() }+ return buffers+ }++ /// Peak level per slice of the recording, 0…1, for the little bar graph.+ static func levels(_ buffers: [AVAudioPCMBuffer], bars: Int) -> [Float] {+ var samples: [Float] = []+ for b in buffers {+ guard let ch = b.floatChannelData?[0] else { continue }+ samples.append(contentsOf: UnsafeBufferPointer(start: ch, count: Int(b.frameLength)))}- if isInstalled {- debugLog("virtual mic: installed")- state = .done- onInstalled?()- } else {- state = .failed("装好了,但系统还没识别到,请稍后再看")+ guard !samples.isEmpty else { return [] }+ let slice = max(1, samples.count / bars)+ return stride(from: 0, to: samples.count, by: slice).prefix(bars).map { start in+ let end = min(samples.count, start + slice)+ return min(1, samples[start..<end].reduce(0) { max($0, abs($1)) })}}}diff --git a/tools/README.md b/tools/README.mdindex b275db4..ebee40e 100644--- a/tools/README.md+++ b/tools/README.md@@ -7,7 +7,8 @@- `lsctl <命令>`:通过分布式通知 `com.wquguru.cicada.debug` 遥控 App。- 开关字幕:`start` / `stop`- - 打开界面:`open`(主窗口)、`panel`(菜单栏面板)、`settings`(设置)+ - 打开界面:`open`(主窗口)、`panel`(菜单栏面板)、`settings[:speak]`(设置,可指定栏目)+ - 虚拟麦克风:`micTest` 试音(往虚拟麦克风播一句再听回来,结果写进日志),`micNext` 做清单里的下一步- 字幕条:`frame` 把位置写进日志,`place:x,y,宽,字号` 摆到指定位置- 说话同传:`speakOn` / `speakOff` 开关,`speakFile:<音频>` 把文件当作麦克风输入,`speakOut:<路径>` 把译文语音另存一份- 导出:`export:<目录>`