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: speak back in Ming's voice through the Ling key, document the AI features

wquguruc6e8a6a88360
diff --git a/AGENTS.md b/AGENTS.md
index 1f578b3..0976981 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -4,13 +4,16 @@ 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, 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.
+- Few surfaces, nothing more: the **menu bar panel** (on/off, heard language, translate-to language, "我说话也翻译", display mode, meeting records, quit), what shows while listening — the **live notes window** (default) or the **subtitle bar** or nothing (`displayMode`) —, the **main window** (meeting records) and a **settings window** (sidebar: 听 / 我说话也翻译 / 显示 / 会议记录 / AI 服务). 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 → notes window caption or subtitle bar. Every confirmed sentence goes into the live meeting record. Translation (`TranslationService`): finished sentences and speak-back go to Ling when a key is set (glossary from the notes' terms), else or on any failure Google, then Apple's on-device `TranslationSession(installedSource:)`; partial text refreshed every second always goes to Google (it would use up Ling's rate limit).
- 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 (changeable) hides/shows. Position, width and size are remembered per display.
+- 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 (changeable) cycles the display mode (notes → bar → none). Position, width and size are remembered per display.
- Speaking: hold the right ⌥ key alone (a listen-only event tap, needs Input Monitoring; any other key while held cancels the press as a chord) or a user-chosen combination (Carbon hotkey, no permission) → 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.
+- AI (Ling, ant-ling.com, OpenAI-compatible): one user key for the whole app, in the login Keychain (`AIKey`, service = bundle id + `.ai`; never in UserDefaults, logs or exports), checked with a one-token `Ling-3.0-tiny` call. `LingClient` is the single gate for every call: request *starts* ≥ 0.6 s apart (the account allows ~2 requests/s across all models), waiting requests ordered speak-back > translation > notes; notes retry 429 with 1/2/4/8 s backoff, translation and speak-back fail fast to the next translator; 401 marks the key invalid. Every call sends `thinking: disabled`, puts the content in the **system** message and a fixed instruction in the user message (otherwise question-like text gets a search-grounded essay instead), and drops replies with no `finish_reason` or starting 根据现有检索证据.
+- Live notes (`NotesEngine`, UI-free): about every 45 s with new lines, one JSON call sends the current notes + new lines (`[L12 02:03 对方] …`) and gets the whole notes back (summary, ≤ 8 topics with points and an optional fishbone, conclusions/to-dos with evidence line ids → support counts, terms with misrecognised forms); a bad reply never replaces good notes. A final pass over the whole transcript runs when the meeting ends ("完整版"). Notes are written in Chinese when Chinese is among the system languages. Stored as `notes` in `session.json`; finished meetings without notes can generate them from the main window. Speak-back can use Ming's voice (`Ming-3.0-tts-0.5B`, SSE PCM 24 kHz) through the same key, falling back to the system voice.
+- Live notes window (`NotesWindow`): a floating `NSPanel`, `sharingType = .none` (invisible to screen sharing and screenshots), on all Spaces, frame autosaved; < 360 px a card with "我刚走神了,错过什么?" (from the topics since it was collapsed), tabs 纪要 / 文字记录 in between, both side by side from 760 px; banners for no key (inline key entry) / invalid key / rate limited.
+- Meeting records: one folder per meeting, `session.json` + `system.m4a` (+ `mic.m4a`); empty meetings are dropped; export to Markdown, Word (`.docx` via `NSAttributedString`, both starting with the notes) and SRT. Speaker labels are only "对方" (system audio) and "你" (microphone): no diarization yet.
- Shortcuts (`Shortcuts.swift`): talk and subtitle-bar toggle are recorded in settings (`ShortcutField`). A combination must include ⌃ or ⌘ (⌥/⇧ alone types characters; bare F keys are brightness/volume), must not be a system shortcut (`CopySymbolicHotKeys`) or held by another app (Carbon refuses to register it).
- Nothing the user does needs the Terminal. When a feature request fits none of the above, push back before adding UI.
@@ -24,7 +27,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`, `Shortcuts` (Carbon `HotKey`, right-⌥ `RightOptionKey`), `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/LiveSubs`: the app. Engine files are UI-free: `SystemAudioTap`, `AudioRouter` (resample, feed, ring buffer, recording), `LanguageDetector`, `ListenEngine`, `SpeakEngine`, `Shortcuts` (Carbon `HotKey`, right-⌥ `RightOptionKey`), `Ling` (Keychain key + client), `Notes` (model + engine), `Translator`, `VirtualMic`, `SessionStore` (+ exports). UI: `Overlay` (subtitle bar), `Views` (panel, main window), `SettingsWindow` (settings + the virtual mic checklist), `AISettings`, `NotesWindow` + `NotesViews` (live notes window; notes and transcript views shared with the main window), `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.
@@ -41,7 +44,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>`, `settings:<listen|speak|overlay|records>`, `micTest`, `micNext`, `talkKey:<right|keyCode:mods>`, `toggleKey:<keyCode:mods>`, `shortcuts`, `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`, `talkKey:<right|keyCode:mods>`, `toggleKey:<keyCode:mods>`, `shortcuts`, `aiKeyFile:<path>` (key from a 0600 file, never through the log), `aiCheck`, `aiRemove`, `aiState`, `lingSimulate:<429|hijack|timeout|off>`, `voice:<ming|system>`, `display:<notes|bar|none>`, `notesWindow[:x,y,w,h]`, `notesFrame`, `notesNow`, `notesState`, `notesShow:<id>`, `notesReplay:<id>`, `notesRender:<png>`, `notesCapturable`, `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.
@@ -49,7 +52,7 @@ Only Command Line Tools are required (no Xcode project). Do not add an `.xcodepr
## Verifying changes
-Run the app and check the behaviour, not just the build. The pattern used so far: dev build, `tools/lsctl` to drive it, `afplay Resources/sample/sample.m4a` (or `say -o` clips) as the "someone talking" input, read `/tmp/livesubs-dev-debug.log`, screenshot windows with `screencapture -l <id>` (`tools/winall`). Synthetic mouse/key events (`tools/mouse`, `tools/key`, `tools/toggle-key`) need the terminal to have Accessibility access. Synthetic keys reach every app: another app's launcher may take ⌥ Space. The real microphone, the BlackHole install (password), granting Input Monitoring and a Mac without permissions need a person.
+Run the app and check the behaviour, not just the build. The pattern used so far: dev build, `tools/lsctl` to drive it, `afplay Resources/sample/sample.m4a` (or `say -o` clips) as the "someone talking" input, read `/tmp/livesubs-dev-debug.log`, screenshot windows with `screencapture -l <id>` (`tools/winall`). Synthetic mouse/key events (`tools/mouse`, `tools/key`, `tools/toggle-key`) need the terminal to have Accessibility access. The notes window is excluded from screen capture: send `notesCapturable` before `screencapture -l`, or `notesRender:<png>` for the whole notes column. Ling tests need a key: `aiKeyFile:` a 0600 file in the scratchpad, deleted right after. Synthetic keys reach every app: another app's launcher may take ⌥ Space. The real microphone, the BlackHole install (password), granting Input Monitoring and a Mac without permissions need a person.
TODO: unit tests for the pure parts (language-code mapping, detection scoring, SRT/Markdown export). Swift Testing under Command Line Tools needs extra framework search paths (see cameo's `scripts/test.sh`).
@@ -58,6 +61,6 @@ TODO: unit tests for the pure parts (language-code mapping, detection scoring, S
- Keep files small and single-purpose; match the existing naming and comment density (comments say why).
- UI and engine state are `@MainActor`; audio callbacks never touch app state directly (they hand buffers to `AudioRouter`'s queue).
- No third-party dependencies; system frameworks only.
-- User data: `~/Library/Application Support/LiveSubs/Sessions` and `UserDefaults` (`sourceMode`, `target`, `speakEnabled`, `speakFrom`, `speakTo`, `speakOutput`, `recordAudio`, `overlayAuto`, `overlayHideAfter`, `overlay.<screen>`, `lastDetected`, `onboarded`, `talkKey`, `toggleKey` as `keyCode:carbonModifiers`).
+- User data: `~/Library/Application Support/LiveSubs/Sessions` and `UserDefaults` (`sourceMode`, `target`, `speakEnabled`, `speakFrom`, `speakTo`, `speakOutput`, `recordAudio`, `overlayAuto`, `overlayHideAfter`, `overlay.<screen>`, `lastDetected`, `onboarded`, `talkKey`, `toggleKey` as `keyCode:carbonModifiers`, `displayMode`, `aiModel`, `speakVoice`) and the Keychain item for the Ling key.
- Add a line to `CHANGELOG.md` with every user-visible change. Keep `README.md` and `README.zh-CN.md` in step.
- Commit in coherent batches with a short imperative subject.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5fd0e23..1f4213e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ the release workflow publishes it as the release notes.
- 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.
- Changed: hold the right ⌥ key on its own to talk, instead of ⌥ Space (which other apps' launchers often use, and which types a space). Pressing another key while holding it cancels, so ⌥ + letter still types. It needs the "输入监控" permission; the app asks for it.
+- New: speak-back can use Ming's voice through the Ling key (Settings › AI 服务 › 我说话时的声音), streamed as it is generated; without a key it uses the system voice.
- New: meeting records show the notes (纪要 / 文字记录); a meeting recorded without notes gets a "生成纪要" button. Markdown and Word exports start with the notes.
- New: a live notes window, now the default display while listening: notes, the transcript and a caption line in one floating window that can be moved and resized anywhere (a small card under 360 px with "我刚走神了,错过什么?", tabs in between, notes beside the transcript from 760 px), never shows up in screen sharing, and remembers its frame. The menu bar panel and settings choose 实时纪要 / 字幕条 / 不显示; ⌃⌥S now cycles through them.
- New: live meeting notes. With a key, Ling updates the notes about every 45 s while the meeting runs (summary, topics with key points, a fishbone diagram where causes are discussed, conclusions and to-dos with how many lines back them, names and terms with their misrecognised forms) and rewrites them once over the whole transcript when it ends. Notes are saved with the meeting.
diff --git a/README.md b/README.md
index d1cb005..ae217cc 100644
--- a/README.md
+++ b/README.md
@@ -33,6 +33,7 @@ Live Subs listens to what your Mac is playing — a livestream, a video, a meeti
- **Detects the language for you** — every installed on-device speech model listens to the same few seconds; the most confident one wins, usually within half a second.
- **Translates into your language** — follows your system languages by default (English audio on an English Mac goes to your next language), or pick one.
- **Stays out of the way** — the subtitle bar appears only while someone talks, tucks into a small dot when it's quiet, and turns see-through when your pointer passes over it, so you can still click what's underneath. Rest the pointer on it to drag or resize; ⌃⌥S hides it.
+- **Live meeting notes** — with your own [Ling](https://chat.ant-ling.com/open) API key (Settings › AI 服务, kept in the macOS Keychain), a floating notes window fills in while the meeting runs: a summary, topics with key points, a fishbone diagram where causes are discussed, conclusions and to-dos, and names spelled consistently. Drag it anywhere, shrink it to a card ("what did I miss?") or widen it to read notes beside the transcript; it never shows up when you share your screen. A full version is written when the meeting ends. The same key makes translation more accurate and can give speak-back Ming's voice; without a key everything else works as before.
- **Speak back** — hold the right ⌥ key and talk; the room hears your words translated, through a virtual microphone you install from the app.
- **Meeting records** — every session is saved as a bilingual transcript (with the audio, on your Mac only) and exports to Markdown, Word or SRT.
- **Private by design** — audio capture, language detection and speech recognition all run on-device.
@@ -62,10 +63,11 @@ The first launch walks you through three steps: turn on **system audio recording
## Usage
-1. Play anything with sound. Subtitles appear at the bottom of the screen.
-2. Click the menu bar icon to change the heard language (auto by default), the language to translate into, or how the subtitle bar behaves.
-3. To speak back: turn on **我说话也翻译**, choose **BlackHole 2ch** as the microphone in your meeting app, then hold the right ⌥ key while you talk (allow "Input Monitoring" when asked). Both shortcuts can be changed in settings.
-4. **会议记录** in the panel opens your transcripts: search, switch between bilingual / original / translation, export.
+1. Play anything with sound. The live notes window shows the transcript and a caption line (choose 字幕条 in the panel for the classic subtitle bar; ⌃⌥S cycles notes / bar / nothing).
+2. Click the menu bar icon to change the heard language (auto by default), the language to translate into, or what is shown.
+3. For notes: paste a Ling API key in Settings › AI 服务 (or right in the notes window). About ¥0.15–1 per hour of meeting at current prices; only text is sent, speech recognition stays on your Mac.
+4. To speak back: turn on **我说话也翻译**, choose **BlackHole 2ch** as the microphone in your meeting app, then hold the right ⌥ key while you talk (allow "Input Monitoring" when asked). Both shortcuts can be changed in settings.
+5. **会议记录** in the panel opens your meetings: notes and transcript, search, export (Markdown and Word start with the notes). A meeting recorded without notes has a "生成纪要" button.
### Uninstall
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 8612b93..867b3e6 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -37,6 +37,7 @@ Live Subs 听电脑里正在播放的声音,比如直播、视频、会议或
- 鼠标经过时字幕条会变透明,下面的按钮照样能点;
- 鼠标停住不动,就可以拖动、缩放字幕条;
- ⌃⌥S 随时隐藏或显示。
+- **实时纪要**:在 设置 › AI 服务 填上自己的 [Ling](https://chat.ant-ling.com/open) API key(加密存在钥匙串里),开会时一个悬浮窗口会边听边整理:总结、议题和要点、讨论原因时的鱼骨图、结论和待办、统一写法的人名。窗口可以拖到任何地方、收成小卡(“我刚走神了,错过什么?”)或拉宽和文字记录并排;共享屏幕时别人看不到它。会议结束后再整理一遍完整版。同一个 key 还让翻译更准,说话时可以用 Ming 的声音;没有 key 时其他功能照常。
- **说话也能翻译**:按住右边的 ⌥ 键说话,会议里的人听到的是翻译后的语音。这需要一个虚拟麦克风,在 App 里一键安装。
- **会议记录**:每场会议都自动存成双语稿子(录音只存在本机),可以导出 Markdown、Word 或 SRT。
- **隐私**:声音采集、语言识别、语音识别都在本机完成。
@@ -70,13 +71,14 @@ Live Subs 听电脑里正在播放的声音,比如直播、视频、会议或
## 使用
-1. 播放任何有声音的内容,字幕会出现在屏幕下方。
-2. 点菜单栏图标,可以改“听到”的语言(默认自动识别)、“翻译成”的语言,以及字幕条的显示方式。
-3. 想让对方听到你的翻译:
+1. 播放任何有声音的内容,实时纪要窗口里会出现文字记录和字幕行。想要原来的字幕条,在面板里选“字幕条”;⌃⌥S 在实时纪要、字幕条、不显示之间切换。
+2. 点菜单栏图标,可以改“听到”的语言(默认自动识别)、“翻译成”的语言,以及显示方式。
+3. 想要纪要:在 设置 › AI 服务(或直接在纪要窗口里)填上 Ling 的 API key。按目前价格一小时会议约 ¥0.15–1;发出去的只有文字,语音识别留在本机。
+4. 想让对方听到你的翻译:
- 打开 **我说话也翻译**;
- 在会议软件里把麦克风选成 **BlackHole 2ch**;
- 说话时按住右边的 ⌥ 键(第一次会请你允许“输入监控”)。两个快捷键都能在设置里换。
-4. 面板里的 **会议记录** 可以看所有稿子:能搜索,能切换双语、原文、译文,也能导出。
+5. 面板里的 **会议记录** 可以看每场会议的纪要和文字记录:能搜索、导出(Markdown 和 Word 开头就是纪要)。没有纪要的会议可以点“生成纪要”。
### 卸载
diff --git a/Sources/LiveSubs/AISettings.swift b/Sources/LiveSubs/AISettings.swift
index 70e6ab1..0f4f307 100644
--- a/Sources/LiveSubs/AISettings.swift
+++ b/Sources/LiveSubs/AISettings.swift
@@ -19,7 +19,14 @@ struct AISettingsView: View {
note: ling.usable ? "会中每 45 秒更新" : "填上 key 才有")
usageRow("翻译", tag: ling.usable ? "用 Ling" : "Google", on: ling.usable,
note: ling.usable ? "整句用 Ling;不行时换 Google、本机" : "没有 key 时照常可用")
- usageRow("语音识别", tag: "本机", on: false, note: "更快,不花钱", divider: false)
+ usageRow("语音识别", tag: "本机", on: false, note: "更快,不花钱")
+ SettingsRow(title: "我说话时的声音", detail: settings.speakVoice == "ming" ? "Ming 声音,首句约 1.3 秒出声" : "系统声音,不用 key", divider: false) {
+ PillMenu(value: settings.speakVoice == "ming" ? "Ming 声音" : "系统声音",
+ options: [("system", "系统声音")] + (ling.usable ? [("ming", "Ming 声音")] : [])) {
+ settings.speakVoice = $0
+ model.applyVoice()
+ }
+ }
}
SettingsCard {
SettingsRow(title: "模型", detail: "3.1 更准;3.0 更快、更省", divider: false) {
diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swift
index d5324c4..3a17a64 100644
--- a/Sources/LiveSubs/AppModel.swift
+++ b/Sources/LiveSubs/AppModel.swift
@@ -88,6 +88,8 @@ final class AppModel: ObservableObject {
await self?.listen.translate(text, source: from, target: to, kind: .speak)
}
speak.roomLanguage = { [weak self] in self?.listen.activeLang?.code }
+ speak.mingVoice = nil
+ applyVoice()
speak.onStatus = { [weak self] text in self?.status = text }
speak.onLive = { [weak self] phase, src, dst in
guard let self else { return }
@@ -404,6 +406,16 @@ final class AppModel: ObservableObject {
return nil
}
+ /// Ming's voice when chosen and a key works; otherwise the system voice.
+ func applyVoice() {
+ speak.mingVoice = settings.speakVoice == "ming" ? { [weak self] text in
+ guard let self, self.ling.usable else {
+ return AsyncThrowingStream { $0.finish(throwing: LingClient.Failure.noKey) }
+ }
+ return self.ling.speech(text)
+ } : nil
+ }
+
func speakFromChanged() {
objectWillChange.send()
if settings.speakEnabled { Task { await speak.prepare() } }
@@ -501,6 +513,9 @@ final class AppModel: ObservableObject {
// Dev testing: the key comes from a file so it never passes through the log.
if let k = try? String(contentsOfFile: arg, encoding: .utf8) { Task { await ling.setKey(k) } }
case "aiCheck": Task { await ling.check() }
+ case "voice":
+ settings.speakVoice = arg == "ming" ? "ming" : "system"
+ applyVoice()
case "notesNow": notes.updateNow()
case "display": setDisplayMode(arg)
case "notesWindow":
diff --git a/Sources/LiveSubs/Ling.swift b/Sources/LiveSubs/Ling.swift
index 2393faa..b63ea9c 100644
--- a/Sources/LiveSubs/Ling.swift
+++ b/Sources/LiveSubs/Ling.swift
@@ -210,6 +210,49 @@ final class LingClient: ObservableObject {
throw Failure.rateLimited
}
+ // MARK: Speech (Ming TTS)
+
+ /// Streams Ming's voice for `text` as raw 24 kHz mono 16-bit PCM chunks.
+ func speech(_ text: String, voice: String = "UK_Charlotte") -> AsyncThrowingStream<Data, Error> {
+ AsyncThrowingStream { cont in
+ let task = Task { @MainActor [weak self] in
+ guard let self, let key = self.key else { cont.finish(throwing: Failure.noKey); return }
+ await self.acquire(.speak)
+ var req = URLRequest(url: Self.base.appendingPathComponent("audio/speech"))
+ req.httpMethod = "POST"
+ req.timeoutInterval = 20
+ req.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ req.httpBody = try? JSONSerialization.data(withJSONObject: [
+ "model": "Ming-3.0-tts-0.5B", "input": text, "voice": voice,
+ "response_format": "pcm", "sample_rate": 24000, "stream": true, "stream_format": "sse",
+ ] as [String: Any])
+ do {
+ let (bytes, response) = try await URLSession.shared.bytes(for: req)
+ switch (response as? HTTPURLResponse)?.statusCode ?? 0 {
+ case 200: break
+ case 401, 403:
+ self.keyState = .invalid
+ throw Failure.invalidKey
+ case 429: throw Failure.rateLimited
+ case let code: throw Failure.http(code)
+ }
+ for try await line in bytes.lines {
+ guard line.hasPrefix("data:"),
+ let obj = try? JSONSerialization.jsonObject(with: Data(line.dropFirst(5).utf8)) as? [String: Any]
+ else { continue }
+ if obj["type"] as? String == "speech.audio.done" { break }
+ if let b64 = obj["audio"] as? String, let pcm = Data(base64Encoded: b64) { cont.yield(pcm) }
+ }
+ cont.finish()
+ } catch {
+ cont.finish(throwing: error)
+ }
+ }
+ cont.onTermination = { _ in task.cancel() }
+ }
+ }
+
// MARK: Transport
private func post(_ path: String, body: [String: Any], key: String, timeout: TimeInterval) async throws -> [String: Any] {
diff --git a/Sources/LiveSubs/Settings.swift b/Sources/LiveSubs/Settings.swift
index a621c13..cadaa1c 100644
--- a/Sources/LiveSubs/Settings.swift
+++ b/Sources/LiveSubs/Settings.swift
@@ -57,6 +57,10 @@ final class AppSettings: ObservableObject {
@Published var displayMode: String {
didSet { save() }
}
+ /// Voice for speak-back: "system" or "ming" (Ming TTS through the Ling key).
+ @Published var speakVoice: String {
+ didSet { save() }
+ }
/// Ling model for notes and translation.
@Published var aiModel: String {
didSet { save() }
@@ -84,6 +88,7 @@ final class AppSettings: ObservableObject {
toggleKey = Shortcut(stored: defaults.string(forKey: "toggleKey")) ?? .defaultToggle
aiModel = defaults.string(forKey: "aiModel") ?? "Ling-3.1-flash"
displayMode = defaults.string(forKey: "displayMode") ?? "notes"
+ speakVoice = defaults.string(forKey: "speakVoice") ?? "system"
}
private func save() {
@@ -103,6 +108,7 @@ final class AppSettings: ObservableObject {
defaults.set(toggleKey.stored, forKey: "toggleKey")
defaults.set(aiModel, forKey: "aiModel")
defaults.set(displayMode, forKey: "displayMode")
+ defaults.set(speakVoice, forKey: "speakVoice")
}
/// Target language. "Follow system" uses the first system language that
diff --git a/Sources/LiveSubs/SpeakEngine.swift b/Sources/LiveSubs/SpeakEngine.swift
index 017e0a6..87f165b 100644
--- a/Sources/LiveSubs/SpeakEngine.swift
+++ b/Sources/LiveSubs/SpeakEngine.swift
@@ -361,7 +361,11 @@ final class SpeakEngine {
}
/// `device` overrides the chosen output (the virtual mic sound test).
+ /// Set by the app: Ming's voice as a PCM stream, when chosen and a key is set.
+ var mingVoice: ((String) -> AsyncThrowingStream<Data, Error>)?
+
func speak(_ text: String, language: String, device override: OutputDevice? = nil) async {
+ if let ming = mingVoice, await speakStream(ming(text), device: override ?? outputDevice()) { return }
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) {
@@ -393,6 +397,51 @@ final class SpeakEngine {
}
/// Core Audio restarted (virtual mic install): device IDs changed, rebuild the output next time.
+ /// Plays 24 kHz mono 16-bit PCM chunks as they arrive. Returns false if nothing came, so the
+ /// caller can fall back to the system voice.
+ private func speakStream(_ stream: AsyncThrowingStream<Data, Error>, device: OutputDevice?) async -> Bool {
+ guard let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 24000, channels: 1, interleaved: false) else { return false }
+ let started = Date()
+ var carry = Data()
+ var count = 0
+ var firstAt: TimeInterval?
+ do {
+ for try await chunk in stream {
+ var bytes = carry + chunk
+ if bytes.count % 2 == 1 { carry = bytes.suffix(1); bytes = bytes.dropLast() } else { carry = Data() }
+ let frames = bytes.count / 2
+ guard frames > 0, let buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(frames)) else { continue }
+ buf.frameLength = AVAudioFrameCount(frames)
+ bytes.withUnsafeBytes { raw in
+ let src = raw.bindMemory(to: Int16.self)
+ let dst = buf.floatChannelData![0]
+ for i in 0..<frames { dst[i] = Float(Int16(littleEndian: src[i])) / 32768 }
+ }
+ if count == 0 {
+ firstAt = Date().timeIntervalSince(started)
+ configureOutput(format: format, device: device)
+ if !out.isRunning { try out.start() }
+ }
+ player.scheduleBuffer(buf, completionHandler: nil)
+ if !player.isPlaying { player.play() }
+ count += 1
+ }
+ } catch {
+ debugLog("ming voice failed: \(error)")
+ if count == 0 { return false }
+ }
+ guard count > 0 else { return false }
+ // Wait for the queued audio to finish before the next utterance.
+ if let tail = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 240) {
+ tail.frameLength = 240
+ await withCheckedContinuation { (cont: CheckedContinuation<Void, Never>) in
+ player.scheduleBuffer(tail, completionCallbackType: .dataPlayedBack) { _ in cont.resume() }
+ }
+ }
+ debugLog("spoke ming \(count) chunks to \(device?.name ?? "default output") first audio \(String(format: "%.2f", firstAt ?? 0)) s")
+ return true
+ }
+
func resetOutput() {
player.stop()
out.stop()