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: add the Try it sound test and simplify the speak-back settings

wquguru372a886dc0e9
diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swift
index 6aa0e54..b607bcd 100644
--- a/Sources/LiveSubs/AppModel.swift
+++ b/Sources/LiveSubs/AppModel.swift
@@ -15,6 +15,15 @@ final class AppModel: ObservableObject {
let toggleKey = HotKey(id: 2, shortcut: .defaultToggle)
lazy var listen = ListenEngine(settings: settings)
lazy var speak = SpeakEngine(settings: settings)
+ lazy var speakTester = SpeakTester(speak: speak, ling: ling, settings: settings)
+ /// Key released → the room heard the first sound, from the latest real press or sound test.
+ @Published var lastSpeakLatency: Double? = UserDefaults.standard.object(forKey: "lastSpeakLatency") as? Double {
+ didSet { UserDefaults.standard.set(lastSpeakLatency, forKey: "lastSpeakLatency") }
+ }
+ /// The 试一句 sheet in settings.
+ @Published var speakTestShown = false
+ /// Settings › 同声传译: the voice list under "对方听到" is open.
+ @Published var voicePickerOpen = false
@Published var running = false
@Published var status = L("准备就绪")
@@ -25,7 +34,11 @@ final class AppModel: ObservableObject {
@Published var speakPhase: SpeakEngine.Phase = .idle
@Published var settingsSection: SettingsSection =
SettingsSection(rawValue: UserDefaults.standard.string(forKey: "settingsSection") ?? "") ?? .speak {
- didSet { UserDefaults.standard.set(settingsSection.rawValue, forKey: "settingsSection") }
+ didSet {
+ UserDefaults.standard.set(settingsSection.rawValue, forKey: "settingsSection")
+ // People pick a voice and move on: don't greet them with the list still open next time.
+ if settingsSection != oldValue { voicePickerOpen = false }
+ }
}
@Published var systemAudioOK = false
@Published var micStatus: AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .audio)
@@ -85,6 +98,11 @@ final class AppModel: ObservableObject {
}
listen.onTiming = { [weak self] in self?.diagnostics.record($0) }
speak.onTiming = { [weak self] in self?.diagnostics.record($0) }
+ speak.onLatency = { [weak self] in self?.lastSpeakLatency = $0 }
+ speakTester.onLatency = { [weak self] in self?.lastSpeakLatency = $0 }
+ speakTester.translate = { [weak self] text, from, to in
+ await self?.listen.translate(text, source: from, target: to, kind: .speak, trace: TranslateTrace())
+ }
ling.onCall = { [weak self] in self?.diagnostics.record($0) }
ling.model = { [weak self] in self?.settings.aiModel ?? "Ling-3.1-flash" }
@@ -113,6 +131,8 @@ final class AppModel: ObservableObject {
speak.onLive = { [weak self] phase, src, dst in
guard let self else { return }
self.speakPhase = phase
+ // A 试一句 rehearsal shows in its own sheet: no notes window, caption or subtitle bar.
+ if self.speakTester.busy { return }
if phase == .listening && !src.isEmpty { self.heardSpeech() }
guard self.settings.displayMode == "bar" else {
// The notes window's caption line shows what you are saying.
@@ -662,7 +682,7 @@ final class AppModel: ObservableObject {
func installDebugControl() {
guard settings.debug || DevBuild.isDev else { return }
DistributedNotificationCenter.default().addObserver(
- forName: Notification.Name("com.wquguru.cicada.debug"), object: nil, queue: .main
+ forName: Notification.Name(DevBuild.debugChannel), object: nil, queue: .main
) { [weak self] note in
let cmd = note.object as? String ?? ""
MainActor.assumeIsolated { self?.debugCommand(cmd) }
@@ -819,6 +839,29 @@ final class AppModel: ObservableObject {
case "speakOff": enableSpeaking(false)
case "speakOut": speak.debugOutputURL = arg.isEmpty ? nil : URL(fileURLWithPath: arg)
case "speakFile": speak.speakFile(URL(fileURLWithPath: arg))
+ case "speakTest":
+ // speakTest:<sample|voice>: open settings › 同声传译 with the 试一句 sheet and run it.
+ settingsSection = .speak
+ openSettingsWindow?()
+ speakTestShown = true
+ speakTester.start(arg == "voice" ? .voice : .sample)
+ case "speakOutput":
+ // speakOutput:<part of a device name>, or empty for the virtual mic (automatic).
+ settings.speakOutput = arg.isEmpty ? "" : AudioDevices.outputs().first { $0.name.localizedCaseInsensitiveContains(arg) }?.uid ?? ""
+ speak.resetOutput()
+ debugLog("speak output=\(speak.outputDevice()?.name ?? "-")")
+ case "voicePicker": voicePickerOpen = arg != "off"
+ case "speakTestBegin": speakTester.beginTalking()
+ case "speakTestEnd": speakTester.endTalking()
+ case "speakTestClose": speakTester.cancel(); speakTestShown = false
+ case "speakTestState":
+ debugLog("speak test phase=\(speakTester.phase) reached=\(String(describing: speakTester.reached)) result=\(speakTester.result?.report.replacingOccurrences(of: "\n", with: " | ") ?? "-")")
+ case "speakTestRender":
+ let r = ImageRenderer(content: SpeakTestView(model: self, tester: speakTester, close: {}).background(Color.white))
+ r.scale = 2
+ if let img = r.nsImage, let tiff = img.tiffRepresentation, let rep = NSBitmapImageRep(data: tiff) {
+ try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: arg))
+ }
case "place":
let n = arg.split(separator: ",").compactMap { Double($0) }
if n.count == 4 { overlay.place(x: n[0], y: n[1], width: n[2], fontSize: n[3]) }
diff --git a/Sources/LiveSubs/DevBuild.swift b/Sources/LiveSubs/DevBuild.swift
index a97fe58..7bd8924 100644
--- a/Sources/LiveSubs/DevBuild.swift
+++ b/Sources/LiveSubs/DevBuild.swift
@@ -16,5 +16,13 @@ enum DevBuild {
/// Folder name under ~/Library/Application Support.
static var supportFolder: String { isDev ? "LiveSubs Dev" : "LiveSubs" }
- static var logPath: String { isDev ? "/tmp/livesubs-dev-debug.log" : "/tmp/livesubs-debug.log" }
+ /// `CICADA_DEBUG_CHANNEL=x` (set with `open --env`, and for `tools/lsctl`) gives one running copy
+ /// its own remote control and log, so two dev builds can be tested side by side.
+ static let channel = ProcessInfo.processInfo.environment["CICADA_DEBUG_CHANNEL"].flatMap { $0.isEmpty ? nil : $0 }
+ static var debugChannel: String { "com.wquguru.cicada.debug" + (channel.map { "." + $0 } ?? "") }
+
+ static var logPath: String {
+ let base = isDev ? "/tmp/livesubs-dev-debug" : "/tmp/livesubs-debug"
+ return base + (channel.map { "-" + $0 } ?? "") + ".log"
+ }
}
diff --git a/Sources/LiveSubs/SettingsWindow.swift b/Sources/LiveSubs/SettingsWindow.swift
index c2e2679..2410b72 100644
--- a/Sources/LiveSubs/SettingsWindow.swift
+++ b/Sources/LiveSubs/SettingsWindow.swift
@@ -450,33 +450,101 @@ struct SettingsView: View {
private var speak: some View {
VStack(alignment: .leading, spacing: 14) {
- Text("按住说话,松开后约 2 秒,对方听到译文").font(.system(size: 12)).foregroundStyle(Palette.secondary)
- .padding(.top, -8)
- SettingsCard { MicSetupCard(installer: installer, deviceName: model.virtualMic?.name) }
- SettingsCard {
- SettingsRow(title: L("把我的话翻译给对方听")) {
- Toggle("把我说的翻译给对方", isOn: Binding(get: { settings.speakEnabled }, set: { model.enableSpeaking($0) }))
- .toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)
+ HStack(spacing: 10) {
+ Text(latencyLine).font(.system(size: 12)).foregroundStyle(Palette.secondary)
+ Spacer(minLength: 8)
+ Button { model.speakTestShown = true } label: {
+ HStack(spacing: 5) {
+ Image(systemName: "play.fill").font(.system(size: 9))
+ Text("试一句").font(.system(size: 12, weight: .semibold))
+ }
+ .foregroundStyle(Color.white).padding(.horizontal, 12).frame(height: 28)
+ .background(RoundedRectangle(cornerRadius: 7).fill(Palette.ink))
+ .contentShape(Rectangle())
}
- SettingsRow(title: L("按住说话"),
- detail: settings.talkKey.isRightOption ? L("单独按住右侧 ⌥;与其他键同时按不会触发") : nil) {
+ .buttonStyle(.plain)
+ .disabled(model.virtualMic == nil)
+ .opacity(model.virtualMic == nil ? 0.4 : 1)
+ .help("说一句话,听对方听到的声音,看每一步花了多久")
+ Toggle("把我说的翻译给对方", isOn: Binding(get: { settings.speakEnabled }, set: { model.enableSpeaking($0) }))
+ .toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)
+ }
+ .padding(.top, -8)
+ SettingsCard {
+ micStep
+ Divider().padding(.leading, 50)
+ HStack(spacing: 12) {
+ StepMark(done: !model.talkNeedsPermission, number: 2)
+ VStack(alignment: .leading, spacing: 2) {
+ Text("按住说话").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
+ Text(settings.talkKey.isRightOption ? L("单独按住右侧 ⌥;和别的键一起按不触发") : L("按住快捷键说话,松开发送"))
+ .font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ }
+ Spacer(minLength: 8)
ShortcutField(model: model, role: .talk)
}
+ .padding(.horizontal, 16).padding(.vertical, 12)
if settings.speakEnabled && model.talkNeedsPermission { TalkKeyPermissionRow(model: model) }
- SettingsRow(title: L("语言"), detail: L("说\(settings.speakFromLang.name),对方听到\(targetName(model.speak.targetCode))")) {
- SoftButton(L("修改")) { model.settingsSection = .language }
- }
- SettingsRow(title: L("声音输出到"), divider: false) {
- PillMenu(value: outputName,
- options: [("", L("虚拟麦克风(自动)"))] + model.outputs.map { ($0.uid, $0.name) }) {
- settings.speakOutput = $0
+ Divider().padding(.leading, 50)
+ VoiceSection(model: model, settings: settings, ling: model.ling)
+ }
+ DisclosureGroup {
+ SettingsCard {
+ SettingsRow(title: L("声音输出到"), detail: L("对方只能听到虚拟麦克风里的声音"), divider: false) {
+ PillMenu(value: outputName,
+ options: [("", L("虚拟麦克风(自动)"))] + model.outputs.map { ($0.uid, $0.name) }) {
+ settings.speakOutput = $0
+ }
}
}
+ .padding(.top, 8)
+ } label: {
+ Text("高级:声音输出到 · \(outputName)").font(.system(size: 12)).foregroundStyle(Palette.secondary)
}
- Text("在会议软件中,将麦克风选为「\(model.virtualMic?.name ?? "BlackHole 2ch")」。")
- .font(.system(size: 12)).foregroundStyle(Palette.secondary).padding(.horizontal, 4)
- VoiceSection(model: model, settings: settings, ling: model.ling).padding(.top, 6)
+ .padding(.horizontal, 4)
}
+ .sheet(isPresented: $model.speakTestShown) {
+ SpeakTestView(model: model, tester: model.speakTester) {
+ if model.speakTester.busy { model.speakTester.cancel() }
+ model.speakTestShown = false
+ }
+ }
+ }
+
+ /// The last measured press, else what to expect.
+ private var latencyLine: String {
+ guard let v = model.lastSpeakLatency else {
+ // Measured with 试一句: Ming's voice ~3 s after release, the Mac's ~1 s.
+ let mac = model.voiceID(for: model.speak.targetCode)?.hasPrefix("system:") ?? true
+ return mac ? L("按住说话,松开后约 1 秒,对方听到译文") : L("按住说话,松开后约 3 秒,对方听到译文")
+ }
+ return L("上次发言:松开后 \(String(format: "%.1f", v)) 秒,对方听到译文")
+ }
+
+ /// Step 1: the checklist until the virtual mic is loaded, then one line.
+ @ViewBuilder
+ private var micStep: some View {
+ if let name = model.virtualMic?.name {
+ HStack(spacing: 12) {
+ StepMark(done: true, number: 1)
+ VStack(alignment: .leading, spacing: 2) {
+ Text("虚拟麦克风").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
+ Text("在会议软件里把麦克风选成「\(name)」").font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ }
+ Spacer(minLength: 8)
+ HStack(spacing: 6) {
+ Circle().fill(micTested ? Palette.ok : Palette.placeholder).frame(width: 8, height: 8)
+ Text(micTested ? L("试音通过") : L("已装好")).font(.system(size: 12)).foregroundStyle(Palette.secondary)
+ }
+ }
+ .padding(.horizontal, 16).padding(.vertical, 12)
+ } else {
+ MicSetupCard(installer: installer, deviceName: nil)
+ }
+ }
+
+ private var micTested: Bool {
+ installer.passed || (model.speakTester.result.map { $0.broken != .room && $0.heardSeconds > 0 } ?? false)
}
private var outputName: String {
diff --git a/Sources/LiveSubs/SpeakEngine.swift b/Sources/LiveSubs/SpeakEngine.swift
index 337186c..038d309 100644
--- a/Sources/LiveSubs/SpeakEngine.swift
+++ b/Sources/LiveSubs/SpeakEngine.swift
@@ -80,7 +80,15 @@ final class SpeakEngine {
var interpret: ((_ wav: Data, _ from: String, _ to: String, _ trace: TranslateTrace) async -> (original: String, translation: String)?)?
/// Diagnostics: key released → transcript → translation → voice finished.
var onTiming: ((SentenceTiming) -> Void)?
+ /// Key released → the first sound of the translation went out, for every real press.
+ var onLatency: ((Double) -> Void)?
+ /// Set by the sound test: the next press is a rehearsal. It reports every stage here and stays
+ /// out of the meeting record and the diagnostics.
+ var probe: SpeakProbe?
private var releasedAt: Date?
+ /// When the latest `speak` call started sending audio, and how it was voiced.
+ private(set) var firstAudioAt: Date?
+ private(set) var lastVoice = ""
/// Language the room speaks (for "follow the room").
var roomLanguage: (() -> String?)?
@@ -110,6 +118,8 @@ final class SpeakEngine {
private let player = AVAudioPlayerNode()
private var outFormat: AVAudioFormat?
private var outDeviceUID: String?
+ /// The device the latest `speak` call played to.
+ private(set) var lastDevice: OutputDevice?
/// Debug: also write synthesized speech here.
var debugOutputURL: URL?
@@ -217,7 +227,7 @@ final class SpeakEngine {
// MARK: Push to talk
func pressBegan() {
- guard settings.speakEnabled, phase == .idle || phase == .speaking else { return }
+ guard settings.speakEnabled || probe != nil, phase == .idle || phase == .speaking else { return }
guard let format = analyzerFormat, let input = beginUtterance() else {
Task { await prepare() }
onStatus?(L("语音识别仍在准备中,请再按一次"))
@@ -256,25 +266,43 @@ final class SpeakEngine {
/// Debug path: feed an audio file as if it were spoken into the mic.
func speakFile(_ url: URL) {
- guard phase == .idle || phase == .speaking else { return }
- guard let format = analyzerFormat, let file = try? AVAudioFile(forReading: url),
- let input = beginUtterance() else {
- debugLog("speakFile: not ready or unreadable \(url.path)")
+ guard let file = try? AVAudioFile(forReading: url) else {
+ debugLog("speakFile: unreadable \(url.path)")
return
}
+ var buffers: [AVAudioPCMBuffer] = []
+ while true {
+ guard let buf = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 4096),
+ (try? file.read(into: buf)) != nil, buf.frameLength > 0 else { break }
+ buffers.append(buf)
+ }
+ Task { await speakBuffers(buffers) }
+ }
+
+ /// Feeds recorded audio in real time, as if someone said it into the mic, then "releases the
+ /// key". Real time matters: fed all at once, recognition would look slower than it is after release.
+ /// Returns false when the engine isn't ready.
+ @discardableResult
+ func speakBuffers(_ buffers: [AVAudioPCMBuffer]) async -> Bool {
+ guard phase == .idle || phase == .speaking, let format = analyzerFormat, let input = beginUtterance() else {
+ debugLog("speakBuffers: not ready")
+ return false
+ }
pressStarted = Date()
phase = .listening
onLive?(.listening, "", "")
let conv = PCMConverter()
- while true {
- guard let buf = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 4096),
- (try? file.read(into: buf)) != nil, buf.frameLength > 0 else { break }
+ for buf in buffers {
if let c = conv.convert(buf, to: format) {
input.yield(AnalyzerInput(buffer: c))
micQueue.sync { keepForMing(c) }
}
+ let seconds = Double(buf.frameLength) / buf.format.sampleRate
+ try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
}
+ releasedAt = Date()
finishUtterance()
+ return true
}
private func startMic(format: AVAudioFormat, input cont: AsyncStream<AnalyzerInput>.Continuation) {
@@ -351,12 +379,16 @@ final class SpeakEngine {
private func finishUtterance() {
stopMic()
phase = .translating
- guard let u = utterance else { phase = .idle; return }
+ let probe = self.probe
+ self.probe = nil
+ guard let u = utterance else { phase = .idle; probe?.finish(); return }
utterance = nil
u.input.finish()
let released = releasedAt ?? Date()
releasedAt = nil
let wav = takePressWAV()
+ probe?.released = released
+ probe?.pressWAV = wav
let from = settings.speakFromLang.code
let to = targetCode
let trace = TranslateTrace()
@@ -374,9 +406,12 @@ final class SpeakEngine {
if let heard { text = heard.original }
// Ming answers recognition and translation together: its whole call counts as `recognize`.
let textAt = Date()
+ probe?.text = text
+ probe?.textAt = textAt
guard !text.isEmpty else {
phase = .idle
onLive?(.idle, "", "")
+ probe?.finish()
return
}
onLive?(.translating, text, "")
@@ -389,6 +424,11 @@ final class SpeakEngine {
result = await translate?(text, from, to, trace)
}
let translatedAt = Date()
+ probe?.translation = result
+ probe?.translatedAt = translatedAt
+ probe?.via = result == nil ? "none" : trace.via
+ probe?.from = from
+ probe?.to = to
@MainActor func timing(voice: Double?) -> SentenceTiming {
SentenceTiming(at: textAt, side: "me", chars: text.count, recognize: textAt.timeIntervalSince(released),
queue: trace.lingQueue, translate: translatedAt.timeIntervalSince(textAt), voice: voice,
@@ -396,18 +436,27 @@ final class SpeakEngine {
}
guard let translated = result else {
debugLog("speak: translation failed, nothing sent")
- onTiming?(timing(voice: nil))
+ if probe == nil { onTiming?(timing(voice: nil)) }
phase = .idle
onLive?(.idle, text, L("翻译失败,这句话未发送"))
+ probe?.finish()
return
}
contentLog("SPEAK [\(from)→\(to)] via=\(trace.via) \(text) => \(translated)")
debugLog("speak: via=\(trace.via) recognize \(String(format: "%.2f", textAt.timeIntervalSince(released))) s translate \(String(format: "%.2f", translatedAt.timeIntervalSince(textAt))) s fallbacks=\(trace.fallbacks)")
- onUtterance?(text, translated, from, to, Date().timeIntervalSince(pressStarted))
+ if probe == nil { onUtterance?(text, translated, from, to, Date().timeIntervalSince(pressStarted)) }
phase = .speaking
onLive?(.speaking, text, translated)
await speak(translated, language: to)
- onTiming?(timing(voice: Date().timeIntervalSince(translatedAt)))
+ if let probe {
+ probe.firstAudioAt = firstAudioAt
+ probe.voice = lastVoice
+ probe.device = lastDevice
+ probe.finish()
+ } else {
+ onTiming?(timing(voice: Date().timeIntervalSince(translatedAt)))
+ if let first = firstAudioAt { onLatency?(first.timeIntervalSince(released)) }
+ }
if phase == .speaking { phase = .idle }
onLive?(.idle, text, translated)
}
@@ -461,10 +510,15 @@ final class SpeakEngine {
/// Mac's voice, so the room always hears the sentence.
func speak(_ text: String, language: String, device override: OutputDevice? = nil, route forced: VoiceRoute? = nil) async {
var voiceID: String?
+ firstAudioAt = nil
+ lastDevice = override ?? outputDevice()
switch forced ?? route?(language) ?? .system(nil) {
case .stream(let make):
+ lastVoice = "ming"
if await speakStream(make(text), device: override ?? outputDevice()) { return }
+ lastVoice = "system (ming failed)"
case .system(let id):
+ lastVoice = "system"
voiceID = id
}
let buffers = await synthesize(text, language: language, voiceID: voiceID)
@@ -488,6 +542,7 @@ final class SpeakEngine {
player.scheduleBuffer(b)
}
}
+ firstAudioAt = Date()
player.play()
}
var cur = AudioObjectID(0); var sz = UInt32(MemoryLayout<AudioObjectID>.size)
@@ -520,6 +575,7 @@ final class SpeakEngine {
}
if count == 0 {
firstAt = Date().timeIntervalSince(started)
+ firstAudioAt = Date()
configureOutput(format: format, device: device)
if !out.isRunning { try out.start() }
}
diff --git a/Sources/LiveSubs/SpeakTest.swift b/Sources/LiveSubs/SpeakTest.swift
new file mode 100644
index 0000000..ebf3dcc
--- /dev/null
+++ b/Sources/LiveSubs/SpeakTest.swift
@@ -0,0 +1,545 @@
+import AVFoundation
+import Foundation
+import Speech
+
+// MARK: - Probe
+
+/// What one rehearsal press went through, filled in by `SpeakEngine` stage by stage.
+@MainActor
+final class SpeakProbe {
+ var released: Date?
+ var pressWAV: Data?
+ var text = ""
+ var textAt: Date?
+ var translation: String?
+ var translatedAt: Date?
+ var via = ""
+ var from = ""
+ var to = ""
+ var firstAudioAt: Date?
+ var voice = ""
+ var device: OutputDevice?
+
+ private var waiters: [CheckedContinuation<Void, Never>] = []
+ private(set) var done = false
+
+ func finish() {
+ guard !done else { return }
+ done = true
+ waiters.forEach { $0.resume() }
+ waiters = []
+ }
+
+ func wait() async {
+ if done { return }
+ await withCheckedContinuation { waiters.append($0) }
+ }
+}
+
+// MARK: - Scoring (pure)
+
+enum SpeakScore {
+ /// Words for comparing what was sent with what came back: CJK by character, others by word,
+ /// lower-cased, punctuation dropped.
+ static func tokens(_ text: String) -> [String] {
+ var out: [String] = []
+ var word = ""
+ func flush() { if !word.isEmpty { out.append(word.lowercased()); word = "" } }
+ for ch in text {
+ if ch.unicodeScalars.contains(where: isCJK) {
+ flush()
+ out.append(String(ch))
+ } else if ch.isLetter || ch.isNumber || ch == "'" || ch == "’" {
+ word.append(ch == "’" ? "'" : ch)
+ } else {
+ flush()
+ }
+ }
+ flush()
+ return out
+ }
+
+ static func isCJK(_ s: Unicode.Scalar) -> Bool {
+ switch s.value {
+ case 0x3040...0x30FF, 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xAC00...0xD7AF, 0xF900...0xFAFF: true
+ default: false
+ }
+ }
+
+ /// Share of the sent words that came back, from the word-level edit distance: 1 = identical.
+ static func match(sent: String, heard: String) -> Double {
+ let a = tokens(sent), b = tokens(heard)
+ guard !a.isEmpty else { return b.isEmpty ? 1 : 0 }
+ var prev = Array(0...b.count)
+ for i in 1...a.count {
+ var cur = [i] + Array(repeating: 0, count: b.count)
+ for j in stride(from: 1, through: b.count, by: 1) {
+ cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] == b[j - 1] ? 0 : 1))
+ }
+ prev = cur
+ }
+ return max(0, 1 - Double(prev[b.count]) / Double(a.count))
+ }
+
+ struct Signal: Equatable {
+ /// Seconds from the start of the recording to the first sound; nil = silence throughout.
+ var onset: Double?
+ var peakDB: Double
+ var clipped: Int
+ var voiced: Double
+ }
+
+ /// Looks at a mono recording in 10 ms windows. The virtual mic is digital: silence is exact
+ /// zeros, so a low threshold finds the first syllable without false starts.
+ static func signal(_ samples: [Float], rate: Double, threshold: Float = 0.003) -> Signal {
+ let window = max(1, Int(rate / 100))
+ var onset: Double?
+ var voicedWindows = 0
+ var peak: Float = 0
+ var clipped = 0
+ var i = 0
+ while i < samples.count {
+ let end = min(samples.count, i + window)
+ var sum: Float = 0
+ for k in i..<end {
+ let v = abs(samples[k])
+ sum += v * v
+ if v > peak { peak = v }
+ if v >= 0.999 { clipped += 1 }
+ }
+ let rms = (sum / Float(end - i)).squareRoot()
+ if rms > threshold {
+ voicedWindows += 1
+ if onset == nil { onset = Double(i) / rate }
+ }
+ i = end
+ }
+ return Signal(onset: onset, peakDB: peak > 0 ? 20 * log10(Double(peak)) : -120,
+ clipped: clipped, voiced: Double(voicedWindows) / 100)
+ }
+
+ /// Bars for the little waveform, 0…1.
+ static func bars(_ samples: [Float], count: Int) -> [Float] {
+ guard !samples.isEmpty, count > 0 else { return [] }
+ let slice = max(1, samples.count / count)
+ return stride(from: 0, to: samples.count, by: slice).prefix(count).map { start in
+ let end = min(samples.count, start + slice)
+ return min(1, samples[start..<end].reduce(0) { max($0, abs($1)) } * 1.4)
+ }
+ }
+
+ /// Ling's verdict: `{"score": 0–100, "issue": "…"}`.
+ static func parseJudge(_ reply: String) -> (score: Int, issue: String)? {
+ guard let start = reply.firstIndex(of: "{"), let end = reply.lastIndex(of: "}"),
+ let data = String(reply[start...end]).data(using: .utf8),
+ let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }
+ let score = (obj["score"] as? NSNumber)?.intValue ?? Int(obj["score"] as? String ?? "")
+ guard let score, (0...100).contains(score) else { return nil }
+ return (score, (obj["issue"] as? String ?? "").trimmingCharacters(in: .whitespaces))
+ }
+}
+
+// MARK: - Result
+
+/// One rehearsal: every stage's output, the timings, and where it broke if it did.
+struct SpeakTestResult {
+ enum Stage: Int, CaseIterable { case mic, recognize, translate, voice, room }
+ enum Meaning: Equatable {
+ case score(Int, String)
+ /// No Ling key: what the room heard, translated back, for the user to judge.
+ case back(String)
+ case unchecked
+ }
+
+ var sample = false
+ var source = ""
+ var translation: String?
+ var heard = ""
+ var from = ""
+ var to = ""
+ var via = ""
+ var voice = ""
+ var outputName = ""
+ var outputIsVirtualMic = true
+ var micPeakDB: Double?
+ var recognize: Double?
+ var translate: Double?
+ var synth: Double?
+ var arrive: Double?
+ /// Key released → the room's first sound, measured on the virtual mic's recording.
+ var firstHeard: Double?
+ var heardSeconds: Double = 0
+ var heardPeakDB: Double = -120
+ var clipped = 0
+ var intelligibility: Double?
+ var meaning: Meaning = .unchecked
+ var broken: Stage?
+ var problem: String?
+ var bars: [Float] = []
+ var heardURL: URL?
+ var micURL: URL?
+
+ var passed: Bool {
+ broken == nil && (intelligibility ?? 1) >= 0.6 && { if case .score(let s, _) = meaning { s >= 60 } else { true } }()
+ }
+
+ /// Timings and checks only, never the words (like the diagnostics report).
+ var report: String {
+ func s(_ v: Double?) -> String { v.map { String(format: "%.2f s", $0) } ?? "-" }
+ var lines = [
+ "\(appDisplayName) speak-back test (\(sample ? "sample" : "voice")) \(from) → \(to)",
+ "verdict: \(passed ? "pass" : "fail")\(broken.map { " at \($0)" } ?? "")",
+ "released → room hears: \(s(firstHeard))",
+ " recognize \(s(recognize)) · translate \(s(translate)) via \(via) · first audio \(s(synth)) · to virtual mic \(s(arrive))",
+ "voice: \(voice) → \(outputName)\(outputIsVirtualMic ? "" : " (not the virtual mic)")",
+ "room audio: \(String(format: "%.1f", heardSeconds)) s, peak \(String(format: "%.0f", heardPeakDB)) dB, clipped \(clipped)",
+ "intelligibility: \(intelligibility.map { "\(Int(($0 * 100).rounded()))%" } ?? "-")",
+ ]
+ if case .score(let v, _) = meaning { lines.append("meaning: \(v)/100") }
+ if let micPeakDB { lines.append("mic peak: \(String(format: "%.0f", micPeakDB)) dB") }
+ return lines.joined(separator: "\n")
+ }
+}
+
+// MARK: - Tester
+
+/// "试一句": one real press through the whole speak-back chain, with the virtual mic's input side
+/// recorded so the user hears exactly what the meeting app receives, then scored without them:
+/// signal on the virtual mic, the recording transcribed again on this Mac and compared with the
+/// translation that was sent, and (with a Ling key) whether the meaning survived.
+@MainActor
+final class SpeakTester: ObservableObject {
+ enum Mode: String { case voice, sample }
+ enum Phase: Equatable {
+ case idle
+ case preparing
+ /// Voice mode: waiting for the user to speak (button or talk key).
+ case ready
+ case talking
+ /// The chain is running; `reached` says how far.
+ case working
+ case scoring
+ case done
+ }
+
+ @Published private(set) var phase: Phase = .idle
+ @Published private(set) var reached: SpeakTestResult.Stage?
+ @Published private(set) var result: SpeakTestResult?
+ @Published private(set) var playing: URL?
+ @Published var mode: Mode = .voice
+
+ let speak: SpeakEngine
+ let ling: LingClient
+ let settings: AppSettings
+ /// The app's translation chain (for the back-translation without a Ling key).
+ var translate: ((_ text: String, _ from: String, _ to: String) async -> String?)?
+ /// A real press measured end to end.
+ var onLatency: ((Double) -> Void)?
+
+ private var probe: SpeakProbe?
+ private var recorder: LoopbackRecorder?
+ private var player: AVAudioPlayer?
+ private var running: Task<Void, Never>?
+
+ var busy: Bool { ![.idle, .done].contains(phase) }
+
+ init(speak: SpeakEngine, ling: LingClient, settings: AppSettings) {
+ self.speak = speak
+ self.ling = ling
+ self.settings = settings
+ }
+
+ static func sampleSentence(for code: String) -> String {
+ switch VoiceCatalog.key(for: code) {
+ case "zh": "我们下周三把方案定下来,然后再约一次评审。"
+ case "ja": "来週の水曜日に計画を決めて、もう一度レビューしましょう。"
+ case "ko": "다음 주 수요일에 계획을 확정하고 다시 검토합시다."
+ case "es": "Cerremos el plan el próximo miércoles y luego hagamos otra revisión."
+ case "fr": "Finalisons le plan mercredi prochain, puis refaisons une revue."
+ case "de": "Lass uns den Plan nächsten Mittwoch festlegen und dann noch einmal prüfen."
+ case "pt": "Vamos fechar o plano na próxima quarta e depois fazer outra revisão."
+ default: "Let's finalize the plan next Wednesday, then set up another review."
+ }
+ }
+
+ // MARK: Run
+
+ func start(_ mode: Mode) {
+ guard !busy else { return }
+ self.mode = mode
+ stopPlaying()
+ result = nil
+ reached = nil
+ running = Task { await run(mode) }
+ }
+
+ /// Voice mode: the on-screen button, same as holding the talk key.
+ func beginTalking() {
+ guard phase == .ready else { return }
+ phase = .talking
+ speak.pressBegan()
+ }
+
+ func endTalking() {
+ guard phase == .talking else { return }
+ phase = .working
+ speak.pressEnded()
+ }
+
+ func cancel() {
+ if phase == .talking { speak.pressCancelled() }
+ speak.probe = nil
+ probe?.finish()
+ _ = recorder?.stop()
+ recorder = nil
+ running?.cancel()
+ phase = .idle
+ stopPlaying()
+ }
+
+ private func run(_ mode: Mode) async {
+ phase = .preparing
+ var r = SpeakTestResult()
+ r.sample = mode == .sample
+ await speak.prepare()
+ if AVCaptureDevice.authorizationStatus(for: .audio) == .notDetermined {
+ _ = await AVCaptureDevice.requestAccess(for: .audio)
+ }
+ guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
+ finish(with: r, broken: .mic, problem: L("试音要用麦克风权限,请在系统设置里允许\(appDisplayName)"))
+ return
+ }
+ guard let vm = AudioDevices.virtualMic else {
+ finish(with: r, broken: .room, problem: L("还没有虚拟麦克风,先在上面装好它"))
+ return
+ }
+ let out = speak.outputDevice()
+ r.outputName = out?.name ?? L("默认输出")
+ r.outputIsVirtualMic = out?.uid == vm.uid
+
+ let recorder = LoopbackRecorder()
+ guard recorder.start(deviceID: vm.id) else {
+ finish(with: r, broken: .room, problem: L("打不开虚拟麦克风,点“让系统认出它”后再试"))
+ return
+ }
+ self.recorder = recorder
+ let probe = SpeakProbe()
+ self.probe = probe
+ speak.probe = probe
+
+ switch mode {
+ case .sample:
+ phase = .working
+ let buffers = await Self.synthesize(Self.sampleSentence(for: settings.speakFromLang.code),
+ locale: settings.speakFromLang.locale)
+ guard !buffers.isEmpty, await speak.speakBuffers(buffers) else {
+ speak.probe = nil
+ _ = recorder.stop()
+ finish(with: r, broken: .mic, problem: L("语音识别还没准备好,请稍后再试"))
+ return
+ }
+ case .voice:
+ phase = .ready
+ }
+ await watch(probe)
+ guard !Task.isCancelled, phase != .idle else { return }
+ // The tail of the voice is still in Core Audio's buffers.
+ try? await Task.sleep(nanoseconds: 600_000_000)
+ let heard = recorder.stop()
+ self.recorder = nil
+ phase = .scoring
+ await score(probe, heard: heard, rate: recorder.sampleRate, startedAt: recorder.startedAt, into: &r)
+ finish(with: r)
+ }
+
+ /// Follows the probe so the progress list moves while the chain runs.
+ private func watch(_ probe: SpeakProbe) async {
+ let follow = Task { @MainActor [weak self] in
+ while !Task.isCancelled, !probe.done {
+ if probe.released != nil, self?.phase == .talking || self?.phase == .ready { self?.phase = .working }
+ self?.reached = probe.firstAudioAt != nil ? .voice : probe.translation != nil ? .translate
+ : probe.textAt != nil ? .recognize : probe.released != nil ? .mic : nil
+ try? await Task.sleep(nanoseconds: 100_000_000)
+ }
+ }
+ await probe.wait()
+ follow.cancel()
+ reached = probe.firstAudioAt != nil ? .voice : reached
+ }
+
+ private func score(_ p: SpeakProbe, heard buffers: [AVAudioPCMBuffer], rate: Double, startedAt: Date?,
+ into r: inout SpeakTestResult) async {
+ r.source = p.text
+ r.translation = p.translation
+ r.from = p.from.isEmpty ? settings.speakFromLang.code : p.from
+ r.to = p.to.isEmpty ? speak.targetCode : p.to
+ r.via = p.via
+ r.voice = p.voice
+ if let d = p.device {
+ r.outputName = d.name
+ r.outputIsVirtualMic = d.isVirtualMic
+ }
+ if let released = p.released {
+ r.recognize = p.textAt.map { $0.timeIntervalSince(released) }
+ if let t = p.textAt, let tr = p.translatedAt { r.translate = tr.timeIntervalSince(t) }
+ if let tr = p.translatedAt, let f = p.firstAudioAt { r.synth = f.timeIntervalSince(tr) }
+ }
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("CicadaSpeakTest", isDirectory: true)
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ if !r.sample, let wav = p.pressWAV {
+ let url = dir.appendingPathComponent("mic.wav")
+ try? wav.write(to: url)
+ r.micURL = url
+ r.micPeakDB = Self.peakDB(wav: wav)
+ }
+
+ var samples: [Float] = []
+ for b in buffers { if let ch = b.floatChannelData?[0] { samples.append(contentsOf: UnsafeBufferPointer(start: ch, count: Int(b.frameLength))) } }
+ let sig = SpeakScore.signal(samples, rate: rate)
+ r.heardSeconds = sig.voiced
+ r.heardPeakDB = sig.peakDB
+ r.clipped = sig.clipped
+ r.bars = SpeakScore.bars(samples, count: 56)
+ if let onset = sig.onset, let startedAt, let released = p.released {
+ let at = startedAt.addingTimeInterval(onset)
+ r.firstHeard = at.timeIntervalSince(released)
+ if let f = p.firstAudioAt { r.arrive = at.timeIntervalSince(f) }
+ }
+ if !samples.isEmpty, let first = buffers.first {
+ let url = dir.appendingPathComponent("heard.wav")
+ try? FileManager.default.removeItem(at: url)
+ if let f = try? AVAudioFile(forWriting: url, settings: first.format.settings) {
+ for b in buffers { try? f.write(from: b) }
+ r.heardURL = url
+ }
+ }
+
+ // Where it broke: the first stage with nothing coming out.
+ if !r.sample, (r.micPeakDB ?? -120) < -50 {
+ r.broken = .mic
+ r.problem = L("麦克风几乎没收到声音:检查系统设置里的输入设备")
+ } else if p.text.isEmpty {
+ r.broken = .recognize
+ r.problem = L("没听出说了什么:靠近麦克风再说一次")
+ } else if p.translation == nil {
+ r.broken = .translate
+ r.problem = L("翻译没有成功:检查网络,或稍后再试")
+ } else if p.firstAudioAt == nil {
+ r.broken = .voice
+ r.problem = L("没有合成出声音:换一个声音再试")
+ } else if sig.onset == nil {
+ r.broken = .room
+ r.problem = r.outputIsVirtualMic ? L("声音没进虚拟麦克风:点“再试音”或重新让系统认出它")
+ : L("「声音输出到」是「\(r.outputName)」,对方只能听到虚拟麦克风里的声音")
+ }
+ if r.broken == nil, let sent = p.translation {
+ phase = .scoring
+ r.heard = await Self.transcribe(buffers, code: r.to)
+ r.intelligibility = r.heard.isEmpty ? nil : SpeakScore.match(sent: sent, heard: r.heard)
+ r.meaning = await judge(original: p.text, from: r.from, heard: r.heard.isEmpty ? sent : r.heard, to: r.to)
+ if r.clipped > 200 { r.problem = L("声音有削波,对方可能听到破音") }
+ else if let i = r.intelligibility, i < 0.6 { r.problem = L("对方那边听写出来差别较大,可能听不清") }
+ else if case .score(let s, let issue) = r.meaning, s < 60 { r.problem = issue.isEmpty ? L("意思可能走样了") : issue }
+ }
+ debugLog("speak test: \(r.report.replacingOccurrences(of: "\n", with: " | "))")
+ contentLog("speak test texts: \(r.source) => \(r.translation ?? "-") => heard \(r.heard)")
+ }
+
+ /// With a Ling key: one small call that scores whether the meaning survived. Without: the
+ /// room's words translated back into the speaker's language, for the user to judge.
+ private func judge(original: String, from: String, heard: String, to: String) async -> SpeakTestResult.Meaning {
+ if ling.usable {
+ let content = """
+ Original (\(TranslationService.englishName(from))): \(original)
+ What the listener heard (\(TranslationService.englishName(to))): \(heard)
+ """
+ let instruction = "Score from 0 to 100 how faithfully what the listener heard conveys the original's meaning. "
+ + "Reply as JSON: {\"score\": <0-100>, \"issue\": \"<the main problem in at most 12 words of \(TranslationService.englishName(from)), or empty>\"}"
+ if let reply = try? await ling.chat(content: content, instruction: instruction, priority: .translate, json: true,
+ maxTokens: 120, timeout: 10),
+ let v = SpeakScore.parseJudge(reply) {
+ return .score(v.score, v.issue)
+ }
+ }
+ if let back = await translate?(heard, to, from), !back.isEmpty { return .back(back) }
+ return .unchecked
+ }
+
+ private func finish(with r: SpeakTestResult, broken: SpeakTestResult.Stage? = nil, problem: String? = nil) {
+ var r = r
+ if let broken { r.broken = broken; r.problem = problem }
+ speak.probe = nil
+ result = r
+ phase = .done
+ probe = nil
+ if let v = r.firstHeard, r.broken == nil { onLatency?(v) }
+ }
+
+ // MARK: Playback
+
+ func play(_ url: URL?) {
+ guard let url else { return }
+ if playing == url { stopPlaying(); return }
+ stopPlaying()
+ player = try? AVAudioPlayer(contentsOf: url)
+ player?.play()
+ playing = url
+ let duration = player?.duration ?? 0
+ Task { @MainActor [weak self] in
+ try? await Task.sleep(nanoseconds: UInt64((duration + 0.2) * 1_000_000_000))
+ if self?.playing == url { self?.playing = nil }
+ }
+ }
+
+ func stopPlaying() {
+ player?.stop()
+ player = nil
+ playing = nil
+ }
+
+ // MARK: Helpers
+
+ private static func peakDB(wav: Data) -> Double {
+ guard wav.count > 44 else { return -120 }
+ var peak: Int32 = 0
+ wav.dropFirst(44).withUnsafeBytes { raw in
+ for s in raw.bindMemory(to: Int16.self) { peak = max(peak, abs(Int32(Int16(littleEndian: s)))) }
+ }
+ return peak > 0 ? 20 * log10(Double(peak) / 32768) : -120
+ }
+
+ /// A sentence in the speaker's language in the Mac's voice: the "sample" input.
+ private static func synthesize(_ text: String, locale: String) async -> [AVAudioPCMBuffer] {
+ let synth = AVSpeechSynthesizer()
+ let u = AVSpeechUtterance(string: text)
+ let lang = locale.hasPrefix("zh") ? "zh-CN" : locale
+ u.voice = AVSpeechSynthesisVoice.speechVoices().filter { $0.language == lang && !$0.voiceTraits.contains(.isNoveltyVoice) }
+ .max { $0.quality.rawValue < $1.quality.rawValue } ?? AVSpeechSynthesisVoice(language: lang)
+ let buffers: [AVAudioPCMBuffer] = await withCheckedContinuation { cont in
+ var out: [AVAudioPCMBuffer] = []
+ var done = false
+ synth.write(u) { buf in
+ guard !done else { return }
+ guard let pcm = buf as? AVAudioPCMBuffer, pcm.frameLength > 0 else {
+ done = true
+ cont.resume(returning: out)
+ return
+ }
+ out.append(pcm)
+ }
+ }
+ _ = synth
+ return buffers
+ }
+
+ /// The room's audio transcribed again in its language, downloading the model if needed.
+ private static func transcribe(_ buffers: [AVAudioPCMBuffer], code: String) async -> String {
+ let locale = sourceLanguages.first { $0.code == code }?.locale ?? (code == "zh-TW" ? "zh-TW" : code)
+ let t = SpeechTranscriber(locale: Locale(identifier: locale), transcriptionOptions: [], reportingOptions: [], attributeOptions: [])
+ if await AssetInventory.status(forModules: [t]) != .installed,
+ let req = try? await AssetInventory.assetInstallationRequest(supporting: [t]) {
+ try? await req.downloadAndInstall()
+ }
+ return await LoopbackTest.transcribe(buffers, locale: locale)
+ }
+}
diff --git a/Sources/LiveSubs/SpeakTestView.swift b/Sources/LiveSubs/SpeakTestView.swift
new file mode 100644
index 0000000..9aabc76
--- /dev/null
+++ b/Sources/LiveSubs/SpeakTestView.swift
@@ -0,0 +1,383 @@
+import AppKit
+import SwiftUI
+
+/// Settings › 同声传译 › 试一句: run one sentence through the real chain, play back what the room
+/// received, show where it broke and how long each stage took.
+struct SpeakTestView: View {
+ @ObservedObject var model: AppModel
+ @ObservedObject var tester: SpeakTester
+ let close: () -> Void
+ @State private var holding = false
+ @State private var copied = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 16) {
+ header
+ switch tester.phase {
+ case .idle: intro
+ case .done: if let r = tester.result { resultView(r) }
+ default: progress
+ }
+ footer
+ }
+ .padding(24)
+ .frame(width: 560, alignment: .leading)
+ .foregroundStyle(Palette.ink)
+ }
+
+ // MARK: Header
+
+ private var header: some View {
+ HStack(alignment: .top, spacing: 10) {
+ if let r = tester.result, tester.phase == .done {
+ Circle().fill(r.passed ? Palette.ok : Palette.accent).frame(width: 10, height: 10).padding(.top, 8)
+ }
+ VStack(alignment: .leading, spacing: 4) {
+ Text(title).font(.system(size: 18, weight: .bold))
+ Text(subtitle).font(.system(size: 12)).foregroundStyle(Palette.secondary)
+ }
+ }
+ }
+
+ private var title: String {
+ guard tester.phase == .done, let r = tester.result else { return L("试一句") }
+ if r.passed { return L("对方听得到,也听得懂") }
+ if r.broken == .room { return L("对方听不到") }
+ if r.broken != nil { return L("这句话没送出去") }
+ return L("对方听得到,但可能听不清")
+ }
+
+ private var subtitle: String {
+ if tester.phase == .done, let r = tester.result {
+ return r.problem ?? L("下面是对方那边收到的原样声音")
+ }
+ return L("走一遍真实流程,录下对方会听到的声音,再放给你听")
+ }
+
+ // MARK: Before
+
+ private var intro: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ Segments(options: [("voice", L("我说一句")), ("sample", L("用示例句子"))], value: tester.mode.rawValue) {
+ tester.mode = SpeakTester.Mode(rawValue: $0) ?? .voice
+ }
+ Text(tester.mode == .voice ? (!talkKeyWorks ? L("点开始后按住按钮,说一句话再松开")
+ : model.settings.talkKey.isRightOption ? L("点开始后按住按钮或右侧 ⌥,说一句话再松开")
+ : L("点开始后按住按钮或说话快捷键,说一句话再松开"))
+ : L("用本机声音读一句\(model.settings.speakFromLang.name):「\(SpeakTester.sampleSentence(for: model.settings.speakFromLang.code))」"))
+ .font(.system(size: 12)).foregroundStyle(Palette.tertiary).fixedSize(horizontal: false, vertical: true)
+ Text("试音会真的送进虚拟麦克风:开会时对方也会听到。")
+ .font(.system(size: 12)).foregroundStyle(Palette.tertiary)
+ }
+ }
+
+ // MARK: Running
+
+ private var progress: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ if tester.phase == .ready || tester.phase == .talking { talkButton }
+ stageList(result: nil)
+ }
+ }
+
+ private var talkButton: some View {
+ let talking = tester.phase == .talking
+ return HStack(spacing: 12) {
+ HStack(spacing: 8) {
+ if talking { LiveDot() } else { Image(systemName: "mic.fill").font(.system(size: 13)) }
+ Text(talking ? L("松开就发送") : L("按住说话")).font(.system(size: 13, weight: .semibold))
+ }
+ .foregroundStyle(talking ? Palette.accentInk : Color.white)
+ .padding(.horizontal, 18).frame(height: 40)
+ .background(RoundedRectangle(cornerRadius: 10).fill(talking ? Palette.accentPale : Palette.ink))
+ .contentShape(Rectangle())
+ .gesture(DragGesture(minimumDistance: 0)
+ .onChanged { _ in if !holding { holding = true; tester.beginTalking() } }
+ .onEnded { _ in holding = false; tester.endTalking() })
+ .accessibilityAddTraits(.isButton)
+ .accessibilityLabel(L("按住说话"))
+ if talkKeyWorks {
+ Text(model.settings.talkKey.isRightOption ? L("或按住右侧 ⌥") : L("或按住说话快捷键"))
+ .font(.system(size: 12)).foregroundStyle(Palette.tertiary)
+ }
+ }
+ }
+
+ private struct StageRow: Identifiable {
+ let id: SpeakTestResult.Stage
+ let name: String
+ let detail: String
+ let time: Double?
+ let state: Int // 0 waiting, 1 running, 2 done, 3 broken
+ var playable: URL?
+ }
+
+ private func stages(_ r: SpeakTestResult?) -> [StageRow] {
+ let reached = tester.reached
+ let running = tester.phase != .done
+ func state(_ s: SpeakTestResult.Stage) -> Int {
+ if let r {
+ if r.broken == s { return 3 }
+ if let b = r.broken, b.rawValue < s.rawValue { return 0 }
+ return 2
+ }
+ guard tester.phase == .working || tester.phase == .scoring else { return s == .mic && tester.phase == .talking ? 1 : 0 }
+ let at = reached?.rawValue ?? -1
+ if s.rawValue <= at { return 2 }
+ return s.rawValue == at + 1 && running ? 1 : 0
+ }
+ let ming = r?.via == "ming"
+ return [
+ StageRow(id: .mic, name: L("你的话"),
+ detail: r.map { $0.sample ? L("示例句子") : $0.micPeakDB.map { L("麦克风峰值 \(Int($0)) dB") } ?? "" } ?? "",
+ time: nil, state: state(.mic), playable: r?.micURL),
+ StageRow(id: .recognize, name: ming ? L("识别 + 翻译") : L("识别"),
+ detail: r.map { $0.source } ?? L("本机转写定稿"), time: r?.recognize, state: state(.recognize)),
+ StageRow(id: .translate, name: L("翻译"),
+ detail: r.map { $0.translation ?? L("没有译文") } ?? "", time: ming ? nil : r?.translate, state: state(.translate)),
+ StageRow(id: .voice, name: L("合成声音"), detail: r.map { voiceName($0) } ?? "", time: r?.synth, state: state(.voice)),
+ StageRow(id: .room, name: L("虚拟麦克风"),
+ detail: r.map { $0.broken == .room ? L("只录到静音") : L("录到 \(String(format: "%.1f", $0.heardSeconds)) 秒声音") }
+ ?? (tester.phase == .scoring ? L("正在重新听写对方收到的声音…") : L("同时录下对方那一侧")),
+ time: r?.arrive.map { max(0, $0) }, state: tester.phase == .scoring && r == nil ? 1 : state(.room), playable: r?.heardURL),
+ ]
+ }
+
+ private func voiceName(_ r: SpeakTestResult) -> String {
+ let v = r.voice.hasPrefix("ming") ? "Ming" : r.voice.contains("failed") ? L("本机(Ming 未成功)") : L("本机声音")
+ return "\(v) → \(r.outputName)"
+ }
+
+ private func stageList(result r: SpeakTestResult?) -> some View {
+ VStack(spacing: 0) {
+ ForEach(Array(stages(r).enumerated()), id: \.element.id) { i, s in
+ HStack(spacing: 12) {
+ ZStack {
+ Circle().fill(s.state == 3 ? Palette.accent : s.state == 2 ? Palette.ink : s.state == 1 ? Palette.accentPale : Palette.fill)
+ switch s.state {
+ case 3: Image(systemName: "xmark").font(.system(size: 9, weight: .bold)).foregroundStyle(.white)
+ case 2: Image(systemName: "checkmark").font(.system(size: 9, weight: .bold)).foregroundStyle(.white)
+ case 1: ProgressView().controlSize(.mini)
+ default: Text("\(i + 1)").font(.system(size: 10, weight: .bold)).foregroundStyle(Palette.tertiary)
+ }
+ }
+ .frame(width: 20, height: 20)
+ Text(s.name).font(.system(size: 13, weight: s.state == 0 ? .regular : .semibold))
+ .foregroundStyle(s.state == 3 ? Palette.accentInk : s.state == 0 ? Palette.tertiary : Palette.ink)
+ .lineLimit(1).fixedSize().frame(minWidth: 92, alignment: .leading)
+ Text(s.detail).font(.system(size: 12)).foregroundStyle(s.state == 3 ? Palette.accentInk : Palette.secondary)
+ .lineLimit(1).truncationMode(.tail).frame(maxWidth: .infinity, alignment: .leading)
+ if let url = s.playable, s.id == .mic {
+ Button(tester.playing == url ? L("停") : L("听")) { tester.play(url) }
+ .buttonStyle(.plain).font(.system(size: 12)).foregroundStyle(Palette.secondary)
+ }
+ if let t = s.time {
+ Text(seconds(t)).font(.system(size: 12, weight: .semibold).monospacedDigit())
+ }
+ }
+ .padding(.vertical, 9)
+ if i < 4 { Divider() }
+ }
+ }
+ .padding(.horizontal, 14)
+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
+ }
+
+ // MARK: Result
+
+ @ViewBuilder
+ private func resultView(_ r: SpeakTestResult) -> some View {
+ if r.broken == nil {
+ VStack(alignment: .leading, spacing: 12) {
+ heardCard(r)
+ checks(r)
+ latency(r)
+ }
+ } else {
+ VStack(alignment: .leading, spacing: 12) {
+ stageList(result: r)
+ fix(r)
+ }
+ }
+ }
+
+ private func heardCard(_ r: SpeakTestResult) -> some View {
+ VStack(alignment: .leading, spacing: 12) {
+ HStack(spacing: 12) {
+ Button { tester.play(r.heardURL) } label: {
+ ZStack {
+ Circle().fill(Palette.accent)
+ Image(systemName: tester.playing == r.heardURL ? "stop.fill" : "play.fill")
+ .font(.system(size: 13)).foregroundStyle(.white)
+ }
+ .frame(width: 40, height: 40)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(L("播放对方听到的声音"))
+ VStack(alignment: .leading, spacing: 2) {
+ Text("听对方听到的").font(.system(size: 13, weight: .semibold))
+ Text("从虚拟麦克风录下的原样声音 · \(String(format: "%.1f", r.heardSeconds)) 秒")
+ .font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ }
+ Spacer()
+ if let url = r.micURL {
+ Button(tester.playing == url ? L("停") : L("听我的原声")) { tester.play(url) }
+ .buttonStyle(.plain).font(.system(size: 12)).foregroundStyle(Palette.secondary)
+ }
+ }
+ HStack(alignment: .center, spacing: 2) {
+ ForEach(Array(r.bars.enumerated()), id: \.offset) { _, v in
+ Capsule().fill(Palette.accent.opacity(0.75)).frame(maxWidth: .infinity).frame(height: max(3, 30 * CGFloat(v)))
+ }
+ }
+ .frame(height: 30)
+ .accessibilityHidden(true)
+ Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 6) {
+ textRow(L("你说"), r.source)
+ textRow(L("送出的译文"), r.translation ?? "")
+ textRow(L("对方那边听写"), r.heard.isEmpty ? L("(没听写出来)") : r.heard)
+ if case .back(let back) = r.meaning { textRow(L("再译回来"), back) }
+ }
+ }
+ .padding(14)
+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
+ }
+
+ private func textRow(_ label: String, _ text: String) -> some View {
+ GridRow {
+ Text(label).font(.system(size: 12)).foregroundStyle(Palette.secondary).gridColumnAlignment(.leading)
+ Text(text).font(.system(size: 13)).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)
+ }
+ }
+
+ private func checks(_ r: SpeakTestResult) -> some View {
+ HStack(spacing: 8) {
+ tile(L("有声"), r.clipped > 200 ? L("有削波") : L("音量正常"), ok: r.clipped <= 200,
+ detail: "\(Int(r.heardPeakDB.rounded())) dB")
+ tile(L("听得清"), r.intelligibility.map { L("\(Int(($0 * 100).rounded()))% 词对上") } ?? L("未检查"),
+ ok: (r.intelligibility ?? 1) >= 0.6, detail: L("本机重新听写"))
+ switch r.meaning {
+ case .score(let s, _): tile(L("意思对"), s >= 60 ? L("一致 \(s)") : L("走样 \(s)"), ok: s >= 60, detail: L("Ling 比对原话"))
+ case .back: tile(L("意思对"), L("请看上面"), ok: true, detail: L("已译回你的语言"))
+ case .unchecked: tile(L("意思对"), L("未检查"), ok: true, detail: L("需要 Ling key"))
+ }
+ }
+ }
+
+ private func tile(_ title: String, _ value: String, ok: Bool, detail: String) -> some View {
+ VStack(alignment: .leading, spacing: 3) {
+ Text(title).font(.system(size: 11)).foregroundStyle(Palette.secondary)
+ HStack(spacing: 4) {
+ Image(systemName: ok ? "checkmark" : "exclamationmark.triangle.fill").font(.system(size: 11, weight: .bold))
+ .foregroundStyle(ok ? Palette.ok : Palette.accent)
+ Text(value).font(.system(size: 14, weight: .bold)).lineLimit(1).minimumScaleFactor(0.8)
+ }
+ Text(detail).font(.system(size: 11)).foregroundStyle(Palette.tertiary).lineLimit(1)
+ }
+ .padding(12)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
+ }
+
+ private func latency(_ r: SpeakTestResult) -> some View {
+ let ming = r.via == "ming"
+ let parts: [(String, Double, Color)] = [
+ (ming ? L("识别 + 翻译") : L("识别"), r.recognize ?? 0, Palette.ink),
+ (L("翻译"), ming ? 0 : r.translate ?? 0, Palette.secondary),
+ (L("合成首音"), r.synth ?? 0, Palette.accent),
+ (L("到达虚拟麦克风"), max(0, r.arrive ?? 0), Palette.placeholder),
+ ].filter { $0.1 > 0.005 }
+ let total = max(0.01, parts.reduce(0) { $0 + $1.1 })
+ return VStack(alignment: .leading, spacing: 10) {
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Text("松开后").font(.system(size: 13, weight: .semibold))
+ Text(r.firstHeard.map(seconds) ?? "-").font(.system(size: 22, weight: .bold).monospacedDigit())
+ Text("对方听到第一个字").font(.system(size: 13)).foregroundStyle(Palette.secondary)
+ }
+ GeometryReader { geo in
+ HStack(spacing: 2) {
+ ForEach(parts, id: \.0) { p in
+ Rectangle().fill(p.2).frame(width: max(2, (geo.size.width - 6) * p.1 / total))
+ }
+ }
+ }
+ .frame(height: 10).clipShape(Capsule())
+ HStack(spacing: 14) {
+ ForEach(parts, id: \.0) { p in
+ HStack(spacing: 4) {
+ RoundedRectangle(cornerRadius: 2).fill(p.2).frame(width: 8, height: 8)
+ Text("\(p.0) \(seconds(p.1))").font(.system(size: 11).monospacedDigit()).foregroundStyle(Palette.secondary)
+ }
+ }
+ }
+ }
+ .padding(14)
+ .background(RoundedRectangle(cornerRadius: 12).fill(Color.white))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.line, lineWidth: 1))
+ }
+
+ @ViewBuilder
+ private func fix(_ r: SpeakTestResult) -> some View {
+ if r.broken == .room {
+ HStack(spacing: 10) {
+ if !r.outputIsVirtualMic {
+ SoftButton(L("改回虚拟麦克风并重试"), dark: true) {
+ model.settings.speakOutput = ""
+ model.speak.resetOutput()
+ tester.start(tester.mode)
+ }
+ } else if AudioDevices.virtualMic != nil {
+ SoftButton(L("让系统认出它"), dark: true) { model.installer.reload() }
+ }
+ // Tells "the voice itself is broken" from "it never reached the room".
+ if let text = r.translation, let id = model.voiceID(for: r.to) {
+ SoftButton(model.previewing == id ? L("正在播放…") : L("在扬声器上听译文")) {
+ model.previewVoice(id, language: r.to, text: text)
+ }
+ .disabled(model.previewing != nil)
+ }
+ }
+ } else if r.broken == .voice {
+ SoftButton(L("换个声音"), dark: true) {
+ model.voicePickerOpen = true
+ close()
+ }
+ } else if r.broken == .translate && !model.ling.usable {
+ Text("没有 Ling key 时用 Google 翻译,需要能访问 Google。").font(.system(size: 12)).foregroundStyle(Palette.tertiary)
+ }
+ }
+
+ // MARK: Footer
+
+ private var footer: some View {
+ HStack(spacing: 10) {
+ switch tester.phase {
+ case .idle:
+ SoftButton(L("取消")) { close() }
+ Spacer()
+ SoftButton(L("开始"), dark: true) { tester.start(tester.mode) }
+ case .done:
+ SoftButton(L("再试一句")) { tester.start(tester.mode) }
+ Button(copied ? L("已复制") : L("复制报告")) {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(tester.result?.report ?? "", forType: .string)
+ copied = true
+ }
+ .buttonStyle(.plain).font(.system(size: 12)).foregroundStyle(Palette.secondary)
+ Spacer()
+ SoftButton(L("完成"), dark: true) { close() }
+ default:
+ Spacer()
+ SoftButton(L("取消")) { tester.cancel(); close() }
+ }
+ }
+ }
+
+ /// The talk key only listens while speak-back is on (and, for the right ⌥, with Input Monitoring).
+ private var talkKeyWorks: Bool { model.settings.speakEnabled && !model.talkNeedsPermission }
+
+ private func seconds(_ v: Double) -> String { L("\(String(format: "%.1f", v)) 秒") }
+}
diff --git a/Sources/LiveSubs/VirtualMic.swift b/Sources/LiveSubs/VirtualMic.swift
index 725a6b6..0db75c3 100644
--- a/Sources/LiveSubs/VirtualMic.swift
+++ b/Sources/LiveSubs/VirtualMic.swift
@@ -238,6 +238,9 @@ final class LoopbackRecorder: @unchecked Sendable {
private var device = AudioObjectID(0)
private var proc: AudioDeviceIOProcID?
private(set) var sampleRate: Double = 48_000
+ /// When the first recorded sample was captured (the first callback, minus its own length).
+ private var firstAt: Date?
+ var startedAt: Date? { lock.lock(); defer { lock.unlock() }; return firstAt }
private let queue = DispatchQueue(label: "com.wquguru.cicada.loopback")
func start(deviceID: AudioObjectID) -> Bool {
@@ -256,6 +259,7 @@ final class LoopbackRecorder: @unchecked Sendable {
let frames = Int(first.mDataByteSize) / MemoryLayout<Float>.size / channels
let p = data.assumingMemoryBound(to: Float.self)
self.lock.lock()
+ if self.firstAt == nil { self.firstAt = Date().addingTimeInterval(-Double(frames) / self.sampleRate) }
for i in 0..<frames { self.samples.append(p[i * channels]) } // first channel is enough
self.lock.unlock()
}
diff --git a/Sources/LiveSubs/VoicePicker.swift b/Sources/LiveSubs/VoicePicker.swift
index 3f19930..58b45e2 100644
--- a/Sources/LiveSubs/VoicePicker.swift
+++ b/Sources/LiveSubs/VoicePicker.swift
@@ -1,8 +1,9 @@
import AVFoundation
import SwiftUI
-/// Settings › 同声传译 › 对方听到的声音: one voice per language the room may speak, each playable,
-/// plus the user's own cloned voice.
+/// Settings › 同声传译, third step "对方听到": the voice for the room's current language as one chip,
+/// opening into a list (any language, the Mac's voices, the user's own cloned voice). Each language
+/// remembers its own choice (`speakVoices`).
struct VoiceSection: View {
@ObservedObject var model: AppModel
@ObservedObject var settings: AppSettings
@@ -17,22 +18,26 @@ struct VoiceSection: View {
private var current: String { tab ?? roomKey }
private var language: String { current == "zh" ? "zh-CN" : current }
private var chosen: String? { model.voiceID(for: language) }
- private static let mainTabs = ["en", "zh", "ja"]
+ private var roomLanguage: String { roomKey == "zh" ? "zh-CN" : roomKey }
var body: some View {
- VStack(alignment: .leading, spacing: 10) {
- HStack {
- Text("对方听到的声音").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.secondary)
- Spacer()
- tabs
- }
- Text("每种语言会记住你选的声音。对方当前在说\(title(roomKey))。")
- .font(.system(size: 12)).foregroundStyle(Palette.tertiary)
- LazyVGrid(columns: [GridItem(.flexible(), spacing: 8), GridItem(.flexible(), spacing: 8)], spacing: 8) {
- ForEach(VoiceCatalog.options(for: language)) { v in card(v) }
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 12) {
+ StepMark(done: true, number: 3)
+ VStack(alignment: .leading, spacing: 2) {
+ Text("对方听到").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
+ // One line of prose with the link inside, so it wraps instead of truncating in English.
+ Text(route)
+ .font(.system(size: 11)).foregroundStyle(Palette.tertiary).tint(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ .environment(\.openURL, OpenURLAction { _ in model.settingsSection = .language; return .handled })
+ }
+ Spacer(minLength: 8)
+ chip
}
- cloneCard
- Text(footnote).font(.system(size: 12)).foregroundStyle(Palette.tertiary).lineSpacing(2)
+ .padding(.horizontal, 16).padding(.vertical, 12)
+ if !ling.usable { keyNudge }
+ if model.voicePickerOpen { picker.padding(.horizontal, 16).padding(.bottom, 14) }
}
.sheet(isPresented: $recording) {
VoiceCloneSheet(model: model, settings: settings, language: language) { saved in
@@ -45,91 +50,137 @@ struct VoiceSection: View {
}
}
- // MARK: Tabs
+ private var route: AttributedString {
+ var text = AttributedString(L("你说\(settings.speakFromLang.name),对方听到\(targetName(model.speak.targetCode))") + " · ")
+ var link = AttributedString(L("改语言"))
+ link.link = URL(string: "cicada-settings:language")
+ link.underlineStyle = .single
+ text.append(link)
+ return text
+ }
- private var tabs: some View {
- HStack(spacing: 2) {
- ForEach(Self.mainTabs, id: \.self) { k in tabButton(k, title(k)) }
- Menu {
- ForEach(VoiceCatalog.languages.filter { !Self.mainTabs.contains($0.key) }, id: \.key) { l in
- Button(l.title) { tab = l.key }
+ // MARK: Chip
+
+ private var roomOption: VoiceOption? {
+ let id = model.voiceID(for: roomLanguage)
+ if id == "clone" { return VoiceCatalog.cloneOption }
+ return VoiceCatalog.options(for: roomLanguage).first { $0.id == id }
+ }
+
+ private var chip: some View {
+ let v = roomOption
+ return HStack(spacing: 8) {
+ playButton(v?.id ?? "", highlighted: true, enabled: v != nil) {
+ if let v { model.previewVoice(v.id, language: roomLanguage) }
+ }
+ Button { withAnimation(.easeOut(duration: 0.15)) { model.voicePickerOpen.toggle(); tab = nil } } label: {
+ HStack(spacing: 6) {
+ Text(v?.name ?? L("系统声音")).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)
+ .lineLimit(1)
+ if let v { Text(summary(v)).font(.system(size: 11)).foregroundStyle(Palette.secondary).lineLimit(1) }
+ Image(systemName: "chevron.down").font(.system(size: 9, weight: .semibold)).foregroundStyle(Palette.tertiary)
+ .rotationEffect(.degrees(model.voicePickerOpen ? 180 : 0))
}
- } label: {
- Text(Self.mainTabs.contains(current) ? L("更多…") : title(current))
- .font(.system(size: 12, weight: Self.mainTabs.contains(current) ? .regular : .semibold))
- .foregroundStyle(Self.mainTabs.contains(current) ? Palette.secondary : Palette.ink)
- .padding(.horizontal, 10).frame(height: 24)
- .background(RoundedRectangle(cornerRadius: 7).fill(Self.mainTabs.contains(current) ? .clear : Color.white))
+ .contentShape(Rectangle())
}
- .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()
+ .buttonStyle(.plain)
+ .accessibilityLabel(L("选择对方听到的声音"))
}
- .padding(3)
- .background(RoundedRectangle(cornerRadius: 9).fill(Color(white: 0.925)))
+ .padding(.leading, 4).padding(.trailing, 10).frame(height: 36)
+ .background(Capsule().fill(Color.white))
+ .overlay(Capsule().stroke(model.voicePickerOpen ? Palette.accent : Palette.line, lineWidth: 1))
+ .fixedSize()
}
- private func tabButton(_ key: String, _ text: String) -> some View {
- let on = current == key
- return Button { tab = key } label: {
- Text(text).font(.system(size: 12, weight: on ? .semibold : .regular))
- .foregroundStyle(on ? Palette.ink : Palette.secondary)
- .padding(.horizontal, 10).frame(height: 24)
- .background(RoundedRectangle(cornerRadius: 7).fill(on ? Color.white : .clear)
- .shadow(color: .black.opacity(on ? 0.06 : 0), radius: 1, y: 1))
- .contentShape(Rectangle())
+ /// "女 · Ming" / "男 · 本机": who it is and where it comes from.
+ private func summary(_ v: VoiceOption) -> String {
+ switch v.kind {
+ case .ming: return [v.tags.first, "Ming"].compactMap { $0 }.joined(separator: " · ")
+ case .system: return [v.tags.first, L("本机")].compactMap { $0 }.joined(separator: " · ")
+ case .clone: return L("你的音色")
}
- .buttonStyle(.plain)
+ }
+
+ private var keyNudge: some View {
+ HStack(spacing: 10) {
+ Text("填入 Ling key:声音更自然,还能用你自己的声音").font(.system(size: 12)).foregroundStyle(Palette.secondary)
+ Spacer(minLength: 6)
+ Button("去填写") { model.settingsSection = .ai }.buttonStyle(.plain)
+ .font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.ink)
+ }
+ .padding(.horizontal, 12).padding(.vertical, 9)
+ .background(RoundedRectangle(cornerRadius: 9).fill(Palette.raised))
+ .padding(.leading, 50).padding(.trailing, 16).padding(.bottom, 12)
+ }
+
+ // MARK: Picker
+
+ private var picker: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack {
+ Text(current == roomKey ? L("每种语言各记一个声音") : L("对方说\(title(current))时用")).font(.system(size: 12))
+ .foregroundStyle(Palette.tertiary)
+ Spacer()
+ PillMenu(value: title(current) + (current == roomKey ? L("(当前)") : ""),
+ options: VoiceCatalog.languages.map { ($0.key, $0.title + ($0.key == roomKey ? L("(当前)") : "")) }) {
+ tab = $0 == roomKey ? nil : $0
+ }
+ }
+ VStack(spacing: 0) {
+ ForEach(VoiceCatalog.options(for: language)) { v in
+ row(v)
+ Divider()
+ }
+ cloneRow
+ }
+ .background(RoundedRectangle(cornerRadius: 10).fill(Color.white))
+ .clipShape(RoundedRectangle(cornerRadius: 10))
+ .overlay(RoundedRectangle(cornerRadius: 10).stroke(Palette.line, lineWidth: 1))
+ Text(footnote).font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ }
+ .padding(.leading, 34)
}
private func title(_ key: String) -> String {
VoiceCatalog.languages.first { $0.key == key }?.title ?? targetName(key)
}
- // MARK: Cards
-
- private func card(_ v: VoiceOption) -> some View {
+ private func row(_ v: VoiceOption) -> some View {
let selected = chosen == v.id
let usable = !v.needsKey || ling.usable
return Button { if usable { model.setVoice(v.id, for: language) } } label: {
HStack(spacing: 10) {
playButton(v.id, highlighted: selected, enabled: usable) { model.previewVoice(v.id, language: language) }
- VStack(alignment: .leading, spacing: 4) {
- Text(v.name).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink).lineLimit(1)
- HStack(spacing: 4) {
- ForEach(usable ? v.tags : [v.tags.first ?? "", L("需要 Ling key")], id: \.self) { tagView($0) }
- }
- }
- Spacer(minLength: 0)
+ Text(v.name).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink).lineLimit(1)
+ .frame(width: 88, alignment: .leading)
+ Text(usable ? v.tags.prefix(2).joined(separator: " · ") + (v.needsKey ? " · Ming" : "") : L("需要 Ling key"))
+ .font(.system(size: 12)).foregroundStyle(Palette.secondary).lineLimit(1)
+ Spacer(minLength: 6)
+ Text(v.needsKey ? L("慢约 1 秒") : L("最快")).font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ Radio(on: selected)
}
- .padding(.horizontal, 12).padding(.vertical, 10)
- .background(RoundedRectangle(cornerRadius: 12).fill(selected ? Palette.accentWash : Color.white))
- .overlay(RoundedRectangle(cornerRadius: 12).stroke(selected ? Palette.accent : Palette.line, lineWidth: selected ? 2 : 1))
- .opacity(usable ? 1 : 0.55)
+ .padding(.horizontal, 10).padding(.vertical, 7)
+ .background(selected ? Palette.accentWash : Color.clear)
+ .opacity(usable ? 1 : 0.5)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityAddTraits(selected ? .isSelected : [])
}
- private func tagView(_ text: String) -> some View {
- Text(text).font(.system(size: 11)).foregroundStyle(Palette.secondary)
- .padding(.horizontal, 6).padding(.vertical, 1)
- .background(RoundedRectangle(cornerRadius: 5).fill(Palette.fill))
- .fixedSize()
- }
-
private func playButton(_ id: String, highlighted: Bool, enabled: Bool, action: @escaping () -> Void) -> some View {
let playing = model.previewing == id
return Button(action: action) {
ZStack {
Circle().fill(highlighted ? Palette.accent : Palette.fill)
if playing {
- Spinner(size: 12, track: highlighted ? Color.white.opacity(0.4) : Palette.accentPale)
+ Spinner(size: 11, track: highlighted ? Color.white.opacity(0.4) : Palette.accentPale)
} else {
- Image(systemName: "play.fill").font(.system(size: 10))
+ Image(systemName: "play.fill").font(.system(size: 9))
.foregroundStyle(highlighted ? Color.white : Palette.ink)
}
}
- .frame(width: 30, height: 30)
+ .frame(width: 28, height: 28)
}
.buttonStyle(.plain)
.disabled(!enabled || playing)
@@ -138,7 +189,7 @@ struct VoiceSection: View {
}
@ViewBuilder
- private var cloneCard: some View {
+ private var cloneRow: some View {
let has = VoiceReference.exists && cloneVersion >= 0
let selected = chosen == "clone"
HStack(spacing: 10) {
@@ -147,47 +198,78 @@ struct VoiceSection: View {
} else {
ZStack {
Circle().fill(Palette.accentPale)
- Image(systemName: "mic").font(.system(size: 13)).foregroundStyle(Palette.accentInk)
+ Image(systemName: "mic").font(.system(size: 12)).foregroundStyle(Palette.accentInk)
}
- .frame(width: 30, height: 30)
+ .frame(width: 28, height: 28)
}
- VStack(alignment: .leading, spacing: 3) {
+ VStack(alignment: .leading, spacing: 2) {
Text("我自己的声音").font(.system(size: 13, weight: .semibold))
- Text(has ? L("已录好 · \(Int(VoiceReference.duration.rounded())) 秒 · \(cloneNote)")
- : L("录制 15 秒原声,让对方听到你的音色;说外语时会保留你的口音,延迟约 3 秒"))
- .font(.system(size: 12)).foregroundStyle(Palette.tertiary).lineLimit(2)
- .fixedSize(horizontal: false, vertical: true)
+ if has {
+ HStack(spacing: 4) {
+ Text("已录 \(Int(VoiceReference.duration.rounded())) 秒 · \(cloneNote)")
+ Text("·")
+ Button("重录") { recording = true }.buttonStyle(.plain).underline()
+ Button("删除") {
+ VoiceReference.remove()
+ for (k, v) in settings.speakVoices where v == "clone" { settings.speakVoices[k] = nil }
+ cloneVersion += 1
+ }
+ .buttonStyle(.plain).underline()
+ }
+ .font(.system(size: 11)).foregroundStyle(Palette.tertiary).lineLimit(1)
+ } else {
+ Text("录 15 秒原声,对方听到你的音色,晚约 3 秒").font(.system(size: 11)).foregroundStyle(Palette.tertiary)
+ }
}
Spacer(minLength: 6)
if has {
- if !selected {
- SoftButton(L("用这个")) { model.setVoice("clone", for: language) }.disabled(!ling.usable)
- }
- Button("重录") { recording = true }.buttonStyle(.plain).font(.system(size: 12)).foregroundStyle(Palette.secondary)
- Button("删除") {
- VoiceReference.remove()
- for (k, v) in settings.speakVoices where v == "clone" { settings.speakVoices[k] = nil }
- cloneVersion += 1
- }
- .buttonStyle(.plain).font(.system(size: 12)).foregroundStyle(Palette.secondary)
+ Button { if ling.usable { model.setVoice("clone", for: language) } } label: { Radio(on: selected) }
+ .buttonStyle(.plain).disabled(!ling.usable)
+ .accessibilityLabel(L("用我自己的声音"))
} else {
- SoftButton(L("录制")) { recording = true }
+ SoftButton(L("录制")) { recording = true }.disabled(!ling.usable)
}
}
- .padding(12)
- .background(RoundedRectangle(cornerRadius: 12).fill(selected ? Palette.accentWash : Color.white))
- .overlay(RoundedRectangle(cornerRadius: 12).stroke(selected ? Palette.accent : Palette.line, lineWidth: selected ? 2 : 1))
+ .padding(.horizontal, 10).padding(.vertical, 8)
+ .background(selected ? Palette.accentWash : Palette.raised)
}
private var cloneNote: String {
let own = VoiceCatalog.key(for: settings.speakFromLang.locale)
- return own == current ? L("说\(title(current))最像你,晚约 3 秒") : L("说\(title(current))会带你的口音,晚约 3 秒")
+ return own == current ? L("最像你") : L("会带你的口音")
}
private var footnote: String {
- if !ling.usable { return L("未填写 Ling key 时仅可使用系统声音;填入 key 后可使用 Ming 语音或克隆你自己的声音。") }
- if chosen == "clone" { return L("录音仅保存在本机,每次发言时随文字发送给 Ling 合成语音;Ling 不可用时自动切回系统声音。") }
- return L("Ming 语音需使用 Ling key,延迟约 1.5 秒;Ling 不可用时自动切回系统声音。")
+ ling.usable ? L("Ling 不可用时自动换成本机声音") : L("填入 Ling key 后可用 Ming 声音和你自己的声音")
+ }
+}
+
+/// A radio dot for list rows.
+struct Radio: View {
+ let on: Bool
+ var body: some View {
+ ZStack {
+ Circle().stroke(on ? Palette.accent : Palette.placeholder, lineWidth: 1.5)
+ if on { Circle().fill(Palette.accent).frame(width: 8, height: 8) }
+ }
+ .frame(width: 16, height: 16)
+ }
+}
+
+/// The numbered circle of a setup step: a check once done.
+struct StepMark: View {
+ let done: Bool
+ let number: Int
+ var body: some View {
+ ZStack {
+ Circle().fill(done ? Palette.ink : Palette.accentPale)
+ if done {
+ Image(systemName: "checkmark").font(.system(size: 10, weight: .bold)).foregroundStyle(.white)
+ } else {
+ Text("\(number)").font(.system(size: 11, weight: .bold)).foregroundStyle(Palette.accentInk)
+ }
+ }
+ .frame(width: 22, height: 22)
}
}
diff --git a/Tests/LiveSubsTests/SpeakScoreTests.swift b/Tests/LiveSubsTests/SpeakScoreTests.swift
new file mode 100644
index 0000000..9b9791e
--- /dev/null
+++ b/Tests/LiveSubsTests/SpeakScoreTests.swift
@@ -0,0 +1,48 @@
+import Foundation
+import Testing
+@testable import LiveSubs
+
+@Suite struct SpeakScoreTests {
+ @Test func tokensSplitCJKByCharacterAndDropPunctuation() {
+ #expect(SpeakScore.tokens("Let's finalize, the PLAN!") == ["let's", "finalize", "the", "plan"])
+ #expect(SpeakScore.tokens("下周三,定下来") == ["下", "周", "三", "定", "下", "来"])
+ #expect(SpeakScore.tokens("Let’s go") == ["let's", "go"])
+ }
+
+ @Test func matchIsOneForSameWordsDespiteCaseAndPunctuation() {
+ #expect(SpeakScore.match(sent: "Let's finalize the plan next Wednesday.", heard: "let's finalize the plan next wednesday") == 1)
+ }
+
+ @Test func matchCountsMissingAndWrongWords() {
+ let m = SpeakScore.match(sent: "one two three four", heard: "one two four")
+ #expect(abs(m - 0.75) < 0.001)
+ #expect(SpeakScore.match(sent: "hello there", heard: "") == 0)
+ #expect(SpeakScore.match(sent: "a b", heard: "x y z w v") == 0)
+ }
+
+ @Test func signalFindsOnsetAfterDigitalSilence() {
+ let rate = 1000.0
+ let tone: [Float] = (0..<300).map { i in Float(sin(Double(i))) * 0.5 }
+ var samples = [Float](repeating: 0, count: 500)
+ samples += tone
+ samples += [Float](repeating: 0, count: 200)
+ let s = SpeakScore.signal(samples, rate: rate)
+ #expect(s.onset == 0.5)
+ #expect(abs(s.voiced - 0.3) < 0.011)
+ #expect(s.clipped == 0)
+ #expect(s.peakDB < 0 && s.peakDB > -7)
+ }
+
+ @Test func signalOfSilenceHasNoOnset() {
+ let s = SpeakScore.signal([Float](repeating: 0, count: 4800), rate: 48_000)
+ #expect(s.onset == nil)
+ #expect(s.voiced == 0)
+ }
+
+ @Test func judgeParsesScoreAndIssue() {
+ #expect(SpeakScore.parseJudge(#"{"score": 92, "issue": ""}"#)! == (92, ""))
+ #expect(SpeakScore.parseJudge("```json\n{\"score\": \"40\", \"issue\": \"date wrong\"}\n```")! == (40, "date wrong"))
+ #expect(SpeakScore.parseJudge(#"{"score": 140}"#) == nil)
+ #expect(SpeakScore.parseJudge("no json") == nil)
+ }
+}
diff --git a/tools/README.md b/tools/README.md
index dd68dd4..a551438 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -11,7 +11,9 @@
- 虚拟麦克风:`micTest` 试音(往虚拟麦克风播一句再听回来,结果写进日志),`micNext` 做清单里的下一步
- 快捷键:`talkKey:right` 或 `talkKey:<keyCode>:<Carbon 修饰键>` 换说话键(被拒的原因写进日志),`toggleKey:…` 同理,`shortcuts` 把当前状态写进日志
- 字幕条:`frame` 把位置写进日志,`place:x,y,宽,字号` 摆到指定位置
- - 说话同传:`speakOn` / `speakOff` 开关,`speakFile:<音频>` 把文件当作麦克风输入,`speakOut:<路径>` 把译文语音另存一份
+ - 说话同传:`speakOn` / `speakOff` 开关,`speakFile:<音频>` 把文件按实时速度当作麦克风输入,`speakOut:<路径>` 把译文语音另存一份,`speakOutput:<设备名片段>` 改输出设备(留空 = 虚拟麦克风)
+ - 试一句:`speakTest:sample`(Mac 读一句示例)或 `speakTest:voice`(再发 `speakTestBegin` / `speakTestEnd` 当作按住、松开),结果以 `speak test:` 写进日志;`speakTestState`、`speakTestRender:<png>`、`speakTestClose`
+ - 多开:两边都设 `CICADA_DEBUG_CHANNEL=x`(`open -n --env CICADA_DEBUG_CHANNEL=x build/Cicada.app`),命令只发给这一份,日志在 `/tmp/livesubs-dev-debug-x.log`
- 导出:`export:<目录>`
- `mouse move|drag|dclick|click|scroll ...`:模拟鼠标移动、拖动、双击、单击、滚轮(`scroll x y 行数`,正数往上翻),坐标原点在主屏左下角。
- `key`:模拟按住说话键。`key right [秒]` 单按右 ⌥;`key <keyCode> <Carbon 修饰键> [秒]` 按组合键(如 `key 122 0` 是 F1);不带参数是 ⌥ Space。
diff --git a/tools/lsctl.swift b/tools/lsctl.swift
index 8b95025..d40367a 100644
--- a/tools/lsctl.swift
+++ b/tools/lsctl.swift
@@ -1,4 +1,6 @@
import Foundation
let cmd = CommandLine.arguments.dropFirst().joined(separator: " ")
-DistributedNotificationCenter.default().postNotificationName(Notification.Name("com.wquguru.cicada.debug"), object: cmd, userInfo: nil, deliverImmediately: true)
+// CICADA_DEBUG_CHANNEL picks one running copy (see DevBuild.debugChannel).
+let channel = ProcessInfo.processInfo.environment["CICADA_DEBUG_CHANNEL"].map { $0.isEmpty ? "" : "." + $0 } ?? ""
+DistributedNotificationCenter.default().postNotificationName(Notification.Name("com.wquguru.cicada.debug" + channel), object: cmd, userInfo: nil, deliverImmediately: true)
RunLoop.main.run(until: Date().addingTimeInterval(0.2))