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(windows): speak into the meeting in its language: hold right Ctrl, the room hears the translation

wquguru584425553f3f
diff --git a/docs/windows-plan.md b/docs/windows-plan.md
index 1957625..7b37051 100644
--- a/docs/windows-plan.md
+++ b/docs/windows-plan.md
@@ -1,6 +1,6 @@
# 知了 Windows 版技术方案
-状态:M1、M2 已在 Windows 11 ARM 虚拟机里跑通(2026-11-04,`windows/vm/`):抓声音不含知了自己、纪要窗不抢焦点也不进截图、引导、字幕条、会议记录、设置、四种界面语言、托盘、再次打开,x64 版在模拟下也跑过;Windows 写的记录和 Mac 格式一致。没测到:真机 x64、125–150% 缩放、蓝牙耳机切换、多显示器、会议软件里的真实屏幕共享。代码和命令见 [windows/README.md](../windows/README.md)。还没做(M3):录音、安装包、签名、自动更新。先做“听”:系统声音 → 实时翻译字幕 → 会议纪要 → 双语记录。“说”(同传进会议)放到后面。
+状态:M1、M2 已在 Windows 11 ARM 虚拟机里跑通(2026-11-04,`windows/vm/`):抓声音不含知了自己、纪要窗不抢焦点也不进截图、引导、字幕条、会议记录、设置、四种界面语言、托盘、再次打开,x64 版在模拟下也跑过;Windows 写的记录和 Mac 格式一致。同声传译(2026-11-04):按住右 Ctrl → Ming 识别并翻译 → Ming 声音(或 Windows 自带)→ VB-Cable;在虚拟机里录下 CABLE Output 核对过中→英、中→日、英→中,以及没翻译成功时什么都不发。没测到:真人麦克风、会议软件里真的选 CABLE Output、真机 x64、125–150% 缩放、蓝牙耳机切换、多显示器、会议软件里的真实屏幕共享。代码和命令见 [windows/README.md](../windows/README.md)。还没做(M3):录音、安装包、签名、自动更新。先做“听”:系统声音 → 实时翻译字幕 → 会议纪要 → 双语记录。“说”(同传进会议)放到后面。
## 范围
diff --git a/windows/README.md b/windows/README.md
index 0002a30..3b724af 100644
--- a/windows/README.md
+++ b/windows/README.md
@@ -1,6 +1,6 @@
# 知了 Windows 版
-Cicada 的 Windows 版,目前只做“听”:把电脑播放的声音变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录。方案和取舍见 [docs/windows-plan.md](../docs/windows-plan.md)。
+Cicada 的 Windows 版:把电脑播放的声音变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录;同声传译(按住右 Ctrl 说话,翻译后的声音经 VB-Cable 虚拟麦克风进会议)。方案和取舍见 [docs/windows-plan.md](../docs/windows-plan.md)。
- 抓声音:WASAPI 进程回环,排除知了自己(Windows 10 2004 起)。
- 识别:Ming(`Ming-3.0-audio-flash`)分段识别,一次请求同时返回语言、原文和译文;需要 Ling key。
@@ -68,3 +68,7 @@ vm/vmctl.sh g shot C:\x.png # Windows 里截图(屏幕共享看到的,不
```
`vmctl.sh g …` 调 `guest.ps1`:SSH 会话没有桌面,要桌面的事(启动、放声音、截图、点击、看前台窗口)都通过计划任务在登录的桌面里做。测不到的:真机 x64、蓝牙耳机切换、多显示器 DPI、会议软件的真实屏幕共享。
+
+## 同声传译怎么测
+
+VM 里没有麦克风:`cicadactl fakemic <wav>` 让按住右 Ctrl 时用这个文件代替麦克风,`speak <wav>` 直接说一句。`record <秒> <wav>` 录下 CABLE Output(会议软件会听到的声音),拷回 Mac 用 `cicada-cli hear` 核对语言和内容。`spike/clips/me-zh.wav`、`me-en.wav` 是“我说的话”,`silence.wav` 用来测什么都不发。
diff --git a/windows/spike/clips/me-en.txt b/windows/spike/clips/me-en.txt
new file mode 100644
index 0000000..8c0df67
--- /dev/null
+++ b/windows/spike/clips/me-en.txt
@@ -0,0 +1 @@
+Can we finish testing before Wednesday?
diff --git a/windows/spike/clips/me-zh.txt b/windows/spike/clips/me-zh.txt
new file mode 100644
index 0000000..fd021c3
--- /dev/null
+++ b/windows/spike/clips/me-zh.txt
@@ -0,0 +1 @@
+我们周三之前能完成测试吗?如果可以,我们就按原计划上线。
diff --git a/windows/src/Cicada.Core/Ling.cs b/windows/src/Cicada.Core/Ling.cs
index bf5d0ac..439e34e 100644
--- a/windows/src/Cicada.Core/Ling.cs
+++ b/windows/src/Cicada.Core/Ling.cs
@@ -220,6 +220,74 @@ public sealed class LingClient
}
}
+ public const string VoiceModel = "Ming-3.0-tts-0.5B";
+
+ /// Ming's voice for `text`: raw 24 kHz mono 16-bit PCM, chunk by chunk as it streams (SSE).
+ /// `languageId` is Ming's `language_id`, needed for ja, ko, de, fr and es. Ling.swift › speech.
+ public async IAsyncEnumerable<byte[]> Speech(string text, string voice, string? languageId = null,
+ [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancel = default)
+ {
+ var k = key.Read() ?? throw new LingException(LingException.Kind.NoKey);
+ if (KeyState == KeyState.Invalid) throw new LingException(LingException.Kind.InvalidKey);
+ var body = new JsonObject
+ {
+ ["model"] = VoiceModel, ["input"] = text, ["voice"] = voice,
+ ["response_format"] = "pcm", ["sample_rate"] = 24000, ["stream"] = true, ["stream_format"] = "sse",
+ };
+ if (languageId is not null) body["language_id"] = languageId;
+ await Acquire(Priority.Speak, cancel);
+ var started = DateTime.UtcNow;
+ using var req = new HttpRequestMessage(HttpMethod.Post, new Uri(Base, "audio/speech"))
+ {
+ Content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json"),
+ };
+ req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", k);
+ using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancel);
+ cts.CancelAfter(TimeSpan.FromSeconds(20));
+ HttpResponseMessage res;
+ try { res = await http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token); }
+ catch (OperationCanceledException) when (!cancel.IsCancellationRequested) { throw new LingException(LingException.Kind.Timeout); }
+ catch (HttpRequestException e) { Log.Debug($"ling: voice network error {e.HttpRequestError}"); throw new LingException(LingException.Kind.Network); }
+ using (res)
+ {
+ switch (res.StatusCode)
+ {
+ case HttpStatusCode.OK: break;
+ case HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden:
+ if (KeyState != KeyState.Invalid) { KeyState = KeyState.Invalid; Changed?.Invoke(); }
+ throw new LingException(LingException.Kind.InvalidKey);
+ case HttpStatusCode.TooManyRequests: throw new LingException(LingException.Kind.RateLimited);
+ default: Log.Debug($"ling: voice HTTP {(int)res.StatusCode}"); throw new LingException(LingException.Kind.Http, (int)res.StatusCode);
+ }
+ using var reader = new StreamReader(await res.Content.ReadAsStreamAsync(cts.Token));
+ int chunks = 0;
+ while (true)
+ {
+ string? line;
+ try { line = await reader.ReadLineAsync(cts.Token); }
+ catch (OperationCanceledException) when (!cancel.IsCancellationRequested) { throw new LingException(LingException.Kind.Timeout); }
+ if (line is null) break;
+ var pcm = SpeechChunk(line, out var done);
+ if (done) break;
+ if (pcm is null) continue;
+ if (chunks++ == 0) Log.Debug($"ling: Speak first audio {(int)(DateTime.UtcNow - started).TotalMilliseconds} ms");
+ yield return pcm;
+ }
+ }
+ }
+
+ /// One SSE line of Ming's voice stream: the PCM it carries, or `done` at the end.
+ public static byte[]? SpeechChunk(string line, out bool done)
+ {
+ done = false;
+ if (!line.StartsWith("data:")) return null;
+ JsonNode? obj;
+ try { obj = JsonNode.Parse(line[5..]); } catch (JsonException) { return null; }
+ if (obj?["type"]?.GetValue<string>() == "speech.audio.done") { done = true; return null; }
+ if (obj?["audio"]?.GetValue<string>() is not { Length: > 0 } b64) return null;
+ try { return Convert.FromBase64String(b64); } catch (FormatException) { return null; }
+ }
+
async Task<JsonNode> Post(string path, string payload, string k, double timeout, CancellationToken cancel)
{
using var req = new HttpRequestMessage(HttpMethod.Post, new Uri(Base, path))
diff --git a/windows/src/Cicada.Core/SessionStore.cs b/windows/src/Cicada.Core/SessionStore.cs
index 6149192..fddd3e4 100644
--- a/windows/src/Cicada.Core/SessionStore.cs
+++ b/windows/src/Cicada.Core/SessionStore.cs
@@ -161,9 +161,9 @@ public sealed class SessionStore
b.AppendLine(s.StartedAt.ToLocalTime().ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)).AppendLine();
if (s.Notes is { IsEmpty: false } n) b.AppendLine($"## {Strings.L("纪要")}").AppendLine().Append(NotesBody(n));
b.AppendLine($"## {Strings.L("文字记录")}").AppendLine();
- foreach (var l in s.Lines)
+ foreach (var l in s.Lines.OrderBy(x => x.T))
{
- b.AppendLine($"**{Languages.Clock(l.T)}** {l.Src} ");
+ b.AppendLine($"**{Languages.Clock(l.T)}**{(l.Speaker == "me" ? $" {Strings.L("你")}:" : "")} {l.Src} ");
if (!string.IsNullOrEmpty(l.Dst) && l.Dst != l.Src) b.AppendLine($"{l.Dst}");
b.AppendLine();
}
diff --git a/windows/src/Cicada.Core/Settings.cs b/windows/src/Cicada.Core/Settings.cs
index c0cca8e..671ea3f 100644
--- a/windows/src/Cicada.Core/Settings.cs
+++ b/windows/src/Cicada.Core/Settings.cs
@@ -20,6 +20,14 @@ public sealed class AppSettings
[JsonPropertyName("uiLanguage")] public string UiLanguage { get; set; } = "system";
/// 字幕文字大小, in px.
[JsonPropertyName("subtitleSize")] public int SubtitleSize { get; set; } = 24;
+ /// 同声传译: hold right Ctrl to speak into the meeting in its language.
+ [JsonPropertyName("speak")] public bool Speak { get; set; }
+ /// 我说的语言: "system" or a source code.
+ [JsonPropertyName("speakFrom")] public string SpeakFrom { get; set; } = "system";
+ /// 对方听到的语言: "room" (what the other side speaks) or a target code.
+ [JsonPropertyName("speakTo")] public string SpeakTo { get; set; } = "room";
+ /// The voice for each language the room hears ("en" → "ming:US_Emma", or "system").
+ [JsonPropertyName("speakVoices")] public Dictionary<string, string> SpeakVoices { get; set; } = [];
/// The one-time "知了还在听" notice after the panel is first collapsed while listening.
[JsonPropertyName("toldStillListening")] public bool ToldStillListening { get; set; }
diff --git a/windows/src/Cicada.Core/Speak.cs b/windows/src/Cicada.Core/Speak.cs
new file mode 100644
index 0000000..808084d
--- /dev/null
+++ b/windows/src/Cicada.Core/Speak.cs
@@ -0,0 +1,223 @@
+using System.Security.Cryptography;
+
+namespace Cicada;
+
+/// Where the room's voice goes: the virtual mic (VB-Cable's "CABLE Input"), or the speakers for a
+/// preview. Takes 16-bit mono PCM at `rate` and returns once it has played.
+public interface ISpeechSink
+{
+ /// Starts a sentence: PCM chunks follow, then End.
+ void Begin(int rate);
+ void Write(byte[] pcm);
+ Task End();
+}
+
+/// Windows' own voice, for when Ming's can't speak: 16-bit mono PCM, or null.
+public interface ISystemVoice
+{
+ Task<(byte[] pcm, int rate)?> Speak(string text, string language);
+ /// Whether this PC has a voice for the language (Chinese Windows often has only Chinese ones).
+ bool Has(string language);
+}
+
+/// A voice the room can hear: one of Ming's (through the Ling key) or Windows' own.
+public sealed record VoiceOption(string Id, string Name, string Tags);
+
+/// Which voices to offer for each language the room may hear: Ming's hand-picked natural ones, as
+/// on the Mac (Voices.swift › VoiceCatalog), then Windows' voice so there is always one.
+public static class VoiceCatalog
+{
+ public const string SystemId = "system";
+
+ public static string Key(string code) { var b = code.Split('-')[0]; return b.Length == 0 ? "en" : b; }
+
+ /// Ming's `language_id` for languages that need it (zh and en work without).
+ public static string? MingLanguage(string code) => Key(code) is "ja" or "ko" or "de" or "fr" or "es" ? Key(code) : null;
+
+ public static IReadOnlyList<VoiceOption> Ming(string language) => Key(language) switch
+ {
+ "en" => [new("ming:US_Emma", "Emma", "女 · 美式 · 自然对话"), new("ming:UK_George", "George", "男 · 英式 · 稳重"), new("ming:UK_Charlotte", "Charlotte", "女 · 英式 · 平稳")],
+ "zh" => [new("ming:灵小雅", "小雅", "女 · 清亮 · 播报"), new("ming:灵小棠", "小棠", "女 · 温和 · 沉稳"), new("ming:灵小锋", "小锋", "男 · 温暖 · 亲切"), new("ming:灵卓然", "卓然", "男 · 沉着 · 清楚")],
+ "ja" or "ko" or "de" or "fr" or "es" => [new("ming:US_Emma", "Emma", "女 · Ming"), new("ming:UK_George", "George", "男 · Ming")],
+ _ => [],
+ };
+
+ public static IReadOnlyList<VoiceOption> Options(string language, bool windowsHasIt = true) =>
+ windowsHasIt ? [.. Ming(language), new(SystemId, "Windows", "本机")] : Ming(language);
+
+ /// What a language uses until the user picks: Ming's first voice with a key, else Windows'.
+ public static string DefaultId(string language, bool hasKey) => hasKey && Ming(language).Count > 0 ? Ming(language)[0].Id : SystemId;
+
+ /// A short line to try a voice with, in the language it will speak.
+ public static string Sample(string language) => Key(language) switch
+ {
+ "zh" => "谢谢大家。我们来看一下上线时间表,并确定谁负责麦克风测试。",
+ "ja" => "皆さん、ありがとうございます。発売スケジュールを確認しましょう。",
+ "ko" => "감사합니다. 출시 일정을 함께 확인해 보겠습니다.",
+ "es" => "Gracias a todos. Revisemos el calendario de lanzamiento.",
+ "fr" => "Merci à tous. Regardons ensemble le calendrier de lancement.",
+ "de" => "Danke an alle. Schauen wir uns den Zeitplan für den Start an.",
+ "pt" => "Obrigado a todos. Vamos ver o cronograma de lançamento.",
+ _ => "Thanks everyone. Let's look at the launch timeline and decide who owns the microphone tests.",
+ };
+}
+
+/// Hold to talk, the Mac's SpeakEngine: what I said (a 16 kHz WAV) → Ming hears and translates it in
+/// one call → a voice speaks the translation into the virtual mic, so the meeting hears it in the
+/// room's language. Never speaks anything untranslated: no translation, no sound.
+public sealed class SpeakEngine
+{
+ public enum Phase { Idle, Recording, Translating, Speaking, Failed }
+
+ readonly LingClient ling;
+ readonly Translator translator;
+ readonly SessionStore store;
+ readonly AppSettings settings;
+ readonly Func<string?> roomLanguage;
+ readonly Func<(string id, DateTimeOffset startedAt)?> openMeeting;
+ readonly ISystemVoice systemVoice;
+ int lineCount;
+ readonly SemaphoreSlim one = new(1, 1);
+
+ public Phase State { get; private set; }
+ /// What the bar shows: what I said, then what the room heard (or why nothing was sent).
+ public string? Said { get; private set; }
+ public string? Heard { get; private set; }
+ public string? Problem { get; private set; }
+ /// "ming" or "system": how the last sentence was voiced.
+ public string? LastVoice { get; private set; }
+ public event Action? Changed;
+
+ public SpeakEngine(LingClient ling, Translator translator, SessionStore store, AppSettings settings,
+ Func<string?> roomLanguage, Func<(string id, DateTimeOffset startedAt)?> openMeeting, ISystemVoice systemVoice)
+ {
+ this.ling = ling; this.translator = translator; this.store = store; this.settings = settings;
+ this.roomLanguage = roomLanguage; this.openMeeting = openMeeting; this.systemVoice = systemVoice;
+ }
+
+ /// The language I speak: the setting, else Windows'.
+ public string MyLanguage => settings.SpeakFrom == "system" ? Languages.FromSystem(System.Globalization.CultureInfo.CurrentUICulture.Name) : settings.SpeakFrom;
+
+ /// The room's language (SpeakEngine.swift › targetCode): the chosen one, else the language the
+ /// other side has been speaking, else English; never my own.
+ public string Target => TargetFor(settings.SpeakTo, roomLanguage(), MyLanguage);
+
+ public static string TargetFor(string speakTo, string? room, string mine)
+ {
+ if (speakTo != "room") return speakTo;
+ var r = room ?? "en";
+ return VoiceCatalog.Key(r) == VoiceCatalog.Key(mine) ? (VoiceCatalog.Key(mine) == "en" ? "zh-CN" : "en") : r;
+ }
+
+ DateTimeOffset? pressedAt;
+
+ public void BeginRecording()
+ {
+ pressedAt = DateTimeOffset.Now;
+ State = Phase.Recording; Said = Heard = Problem = null;
+ Changed?.Invoke();
+ }
+
+ public void Cancel()
+ {
+ if (State == Phase.Recording) { State = Phase.Idle; Changed?.Invoke(); }
+ }
+
+ /// One utterance: `wav` is 16 kHz mono. Returns what the room heard, or null if nothing was sent.
+ public async Task<string?> Speak(byte[] wav, ISpeechSink sink)
+ {
+ await one.WaitAsync();
+ try
+ {
+ var released = DateTime.UtcNow;
+ var to = Target;
+ State = Phase.Translating; Said = Heard = Problem = null;
+ Changed?.Invoke();
+ Heard? heard = null;
+ try { heard = await translator.Hear(wav, to, MyLanguage); }
+ catch (LingException e) { Log.Debug($"speak: hear failed {e.Message}"); return Fail(e.Failure is LingException.Kind.Network or LingException.Kind.Timeout ? Strings.L("连不上 Ling,没有发出去") : Strings.L("没翻译成功,没有发出去")); }
+ if (heard is null) return Fail(Strings.L("没听清,没有发出去"));
+ Said = heard.Original;
+ var text = heard.Translation;
+ // Ming didn't translate it: the text translator gets one try; failing that, silence.
+ if (text is null && heard.Lang != to) text = await translator.Translate(heard.Original, heard.Lang, to, Translator.Kind.Sentence);
+ if (string.IsNullOrWhiteSpace(text)) return Fail(Strings.L("没翻译成功,没有发出去"));
+ var translatedAt = DateTime.UtcNow;
+ Heard = text;
+ State = Phase.Speaking;
+ Changed?.Invoke();
+ Record(heard, text, to, pressedAt ?? DateTimeOffset.Now.AddSeconds(-(wav.Length - 44) / 32000.0));
+ pressedAt = null;
+ var voiced = await Voice(text, to, sink);
+ Log.Debug($"speak: {heard.Lang} → {to} via {LastVoice ?? "nothing"}, translated in {(translatedAt - released).TotalMilliseconds:F0} ms, voiced by {(DateTime.UtcNow - released).TotalMilliseconds:F0} ms");
+ if (!voiced) return Fail(systemVoice.Has(to) ? Strings.L("没能发出声音") : Strings.L("这台电脑没有这种语言的声音,没有发出去"));
+ State = Phase.Idle;
+ Changed?.Invoke();
+ return text;
+ }
+ finally { one.Release(); }
+ }
+
+ /// Something stopped the sentence before it got here (no mic, no virtual mic): say so on the bar.
+ public void Report(string why) => Fail(why);
+
+ string? Fail(string why)
+ {
+ State = Phase.Failed; Problem = why; pressedAt = null;
+ Log.Debug($"speak: nothing sent ({why})");
+ Changed?.Invoke();
+ return null;
+ }
+
+ /// The sentence joins the meeting being listened to, as the Mac's "me" lines do.
+ /// Timed from when I started speaking, like the other side's lines.
+ void Record(Heard heard, string text, string to, DateTimeOffset spokeAt)
+ {
+ if (openMeeting() is not { } m) return;
+ var line = new TranscriptLine
+ {
+ Id = $"m{++lineCount}", T = Math.Max(0, (spokeAt - m.startedAt).TotalSeconds), Speaker = "me",
+ Src = heard.Original, Dst = text, SrcLang = heard.Lang, DstLang = to,
+ };
+ store.Append(m.id, line);
+ }
+
+ /// Ming's voice, else Windows'. True once some sound went out.
+ public async Task<bool> Voice(string text, string language, ISpeechSink sink)
+ {
+ var id = settings.SpeakVoices.TryGetValue(VoiceCatalog.Key(language), out var chosen) ? chosen : VoiceCatalog.DefaultId(language, ling.HasKey);
+ if (id.StartsWith("ming:") && ling.HasKey)
+ {
+ int chunks = 0;
+ try
+ {
+ await foreach (var pcm in ling.Speech(text, id["ming:".Length..], VoiceCatalog.MingLanguage(language)))
+ {
+ if (chunks++ == 0) sink.Begin(24000);
+ sink.Write(pcm);
+ }
+ }
+ catch (LingException e) { Log.Debug($"speak: ming voice failed {e.Message}"); }
+ if (chunks > 0) { await sink.End(); LastVoice = "ming"; return true; }
+ }
+ var own = await systemVoice.Speak(text, language);
+ if (own is not { } v || v.pcm.Length == 0) { LastVoice = null; return false; }
+ sink.Begin(v.rate);
+ sink.Write(v.pcm);
+ await sink.End();
+ LastVoice = "system";
+ return true;
+ }
+}
+
+/// VB-Cable, the virtual mic: downloaded from VB-Audio when the user asks, never bundled, and run
+/// only if it is the exact package checked here (as BlackHole is on the Mac).
+public static class VirtualCable
+{
+ public const string PackageUrl = "https://download.vb-audio.com/Download_CABLE/VBCABLE_Driver_Pack45.zip";
+ public const string PackageSha256 = "b950e39f01af1d04ea623c8f6d8eb9b6ea5c477c637295fabf20631c85116bfb";
+ /// The render endpoint the app writes to, and the capture one meeting apps pick as the mic.
+ public const string InputName = "CABLE Input", OutputName = "CABLE Output";
+
+ public static bool Verify(byte[] package) => Convert.ToHexString(SHA256.HashData(package)).Equals(PackageSha256, StringComparison.OrdinalIgnoreCase);
+}
diff --git a/windows/src/Cicada.Core/Translator.cs b/windows/src/Cicada.Core/Translator.cs
index 2e0a6df..fc40cb1 100644
--- a/windows/src/Cicada.Core/Translator.cs
+++ b/windows/src/Cicada.Core/Translator.cs
@@ -42,7 +42,9 @@ public sealed class Translator(LingClient ling)
public static bool IsFiller(string text)
{
var words = text.ToLowerInvariant().Split([' ', ',', ',', '、', '.', '。', '!', '!', '?', '?', '…', '~', '-'], StringSplitOptions.RemoveEmptyEntries);
- return words.Length > 0 && words.Length <= 3 && words.All(Fillers.Contains);
+ // "呃呃呃呃": the same sound held, which is what Ming makes of near-silence.
+ static bool Held(string w) => w.Length > 1 && w.All(c => c == w[0]) && Fillers.Contains(w[..1]);
+ return words.Length > 0 && words.Length <= 3 && words.All(w => Fillers.Contains(w) || Held(w));
}
public static string HearPrompt(string target, string? hint, IReadOnlyList<string> names)
diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.cs
index 0800253..5f31e6e 100644
--- a/windows/src/Cicada/App.cs
+++ b/windows/src/Cicada/App.cs
@@ -43,6 +43,13 @@ sealed class Controller
public readonly NotesEngine Notes;
public readonly Translator Translator;
public readonly ListenEngine Listen;
+ public readonly SpeakEngine Speak;
+ public readonly WindowsVoice WindowsVoice = new();
+ PushToTalk? talk;
+ SpeakBar? speakBar;
+ DeviceRecorder? mic;
+ /// Dev builds: a WAV that stands in for the microphone (the VM has none).
+ string? fakeMic;
readonly Forms.NotifyIcon tray = new();
System.Drawing.Icon? idleIcon, liveIcon;
Action? balloonClicked;
@@ -63,6 +70,9 @@ sealed class Controller
Notes = new NotesEngine(Ling, Store);
Translator = new Translator(Ling);
Listen = new ListenEngine(Ling, Translator, Store, Notes, Settings);
+ Speak = new SpeakEngine(Ling, Translator, Store, Settings, () => Listen.Spoken,
+ () => Listen.Listening && Listen.SessionId is { } id && Store.Get(id) is { } s ? (id, s.StartedAt) : null, WindowsVoice);
+ Speak.Changed += () => Dispatch.BeginInvoke(() => { speakBar ??= new SpeakBar(this); speakBar.Refresh(); });
Listen.Changed += Changed;
Notes.Changed += Changed;
Store.Changed += _ => Changed();
@@ -80,6 +90,10 @@ sealed class Controller
Log.Debug($"app: launch {(Paths.Dev ? "dev" : "release")} {Environment.OSVersion.Version}");
SetUpTray();
hotkey = new Hotkey(() => Dispatch.BeginInvoke(() => _ = ToggleListening()));
+ talk = new PushToTalk();
+ talk.Pressed += () => Dispatch.BeginInvoke(PressBegan);
+ talk.Released += () => Dispatch.BeginInvoke(PressEnded);
+ Log.Debug($"audio: speakers {Endpoints.Default(Endpoints.Flow.Render)?.Name ?? "none"}, mic {Endpoints.Microphone()?.Name ?? "none"}, cable {(Endpoints.Cable() is null ? "absent" : "present")}");
DebugServer.Start(this);
if (!Settings.Onboarded) new Onboarding(this).Show();
else if (Ling.HasKey) _ = Ling.Check();
@@ -260,6 +274,56 @@ sealed class Controller
await StopListening();
}
+ // MARK: Speaking (同声传译)
+
+ public bool NotesVisible => notesWindow?.IsVisible == true;
+
+ public void SetFakeMic(string? path) { fakeMic = path; Log.Debug($"speak: fake mic {(path is null ? "off" : "on")}"); }
+
+ /// Dev: what the meeting hears. Records "CABLE Output" for `seconds` into `path` ("8 C:\x.wav").
+ public async Task RecordCable(string arg)
+ {
+ var parts = arg.Split(' ', 2);
+ if (parts.Length < 2 || !double.TryParse(parts[0], out var seconds) || Endpoints.CableOutput() is not { } d) { Log.Debug("record: no cable output"); return; }
+ var r = new DeviceRecorder(d.Id);
+ r.Start();
+ await Task.Delay(TimeSpan.FromSeconds(seconds));
+ var pcm = r.Stop();
+ File.WriteAllBytes(parts[1], Wav.Bytes(pcm));
+ double sum = 0; foreach (var x in pcm) sum += (double)x * x;
+ Log.Debug($"record: {pcm.Length / 16000.0:F1} s from {d.Name}, rms {Math.Sqrt(sum / Math.Max(1, pcm.Length)) / 32768:F4}");
+ }
+
+ void PressBegan()
+ {
+ if (!Settings.Speak || Speak.State is SpeakEngine.Phase.Recording or SpeakEngine.Phase.Translating) return;
+ if (!Ling.HasKey) { Speak.Report(L("需要 Ling key 才能说")); return; }
+ if (Endpoints.Cable() is null) { Speak.Report(L("还没装虚拟麦克风,去设置里装一下")); return; }
+ if (fakeMic is null)
+ {
+ if (Endpoints.Microphone() is not { } m) { Speak.Report(L("没找到麦克风")); return; }
+ mic = new DeviceRecorder(m.Id);
+ mic.Start();
+ if (mic.Error is { } err) { mic = null; Speak.Report(err == "denied" ? L("Windows 不让知了用麦克风:设置 › 隐私和安全性 › 麦克风") : L("麦克风打不开")); return; }
+ }
+ Speak.BeginRecording();
+ }
+
+ void PressEnded()
+ {
+ if (Speak.State != SpeakEngine.Phase.Recording) return;
+ var pcm = fakeMic is { } f ? Wav.Read(f) : mic?.Stop() ?? [];
+ mic = null;
+ // A tap, not a sentence.
+ if (pcm.Length < Segmenter.Rate * 3 / 10) { Speak.Cancel(); return; }
+ // Held but nothing said (a muted mic): Ming would make something up from the hiss.
+ if (pcm.Max(x => Math.Abs((int)x)) < 300) { Speak.Report(L("没听到你说话,没有发出去")); return; }
+ _ = Speak.Speak(Wav.Bytes(pcm), new DeviceSpeaker(Endpoints.Cable));
+ }
+
+ /// 试听: a voice speaks its sample line on the speakers (not into the meeting).
+ public Task Preview(string language) => Speak.Voice(VoiceCatalog.Sample(language), language, new DeviceSpeaker(() => Endpoints.Default(Endpoints.Flow.Render)));
+
// MARK: Windows
public void ShowNotes()
@@ -321,6 +385,7 @@ sealed class Controller
if (Listen.Listening) await StopListening();
Store.Flush();
hotkey?.Dispose();
+ talk?.Dispose();
tray.Visible = false;
tray.Dispose();
application.Shutdown();
@@ -343,6 +408,14 @@ sealed class Controller
["showInCapture"] = Settings.ShowInCapture,
["sessions"] = Store.All().Count,
["hotkey"] = HotkeyRegistered,
+ ["speak"] = Settings.Speak,
+ ["speakState"] = Speak.State.ToString(),
+ ["speakTarget"] = Speak.Target,
+ ["said"] = Speak.Said,
+ ["heard"] = Speak.Heard,
+ ["speakProblem"] = Speak.Problem,
+ ["voice"] = Speak.LastVoice,
+ ["cable"] = Endpoints.Cable() is not null,
["autostart"] = AutoStart.Enabled,
};
}
@@ -403,6 +476,13 @@ static class DebugServer
break;
case "toast": app.Toast(L("纪要整理好了"), LF("%@ · 点这里打开", "Test"), () => app.ShowRecords()); break;
case "problem": app.Listen.SimulateProblem(arg); break;
+ case "speak":
+ if (arg == "on" || arg == "off") { app.Settings.Speak = arg == "on"; app.Settings.Save(); app.SettingsChanged(); }
+ else _ = app.Speak.Speak(Wav.Bytes(Wav.Read(arg)), new DeviceSpeaker(Endpoints.Cable));
+ break;
+ case "fakemic": app.SetFakeMic(arg == "off" ? null : arg); break;
+ case "record": _ = app.RecordCable(arg); break;
+ case "preview": _ = app.Preview(arg.Length > 0 ? arg : app.Speak.Target); break;
case "quit": _ = app.Quit(); break;
case "state": break;
default: return new JsonObject { ["error"] = $"unknown command {parts[0]}" };
diff --git a/windows/src/Cicada/Dialogs.cs b/windows/src/Cicada/Dialogs.cs
index 4129400..cde48e0 100644
--- a/windows/src/Cicada/Dialogs.cs
+++ b/windows/src/Cicada/Dialogs.cs
@@ -17,6 +17,9 @@ static class Dialogs
return Show(owner, title, text, ok, danger, null) is not null;
}
+ /// Something to know, with one button.
+ public static void Tell(Window owner, string title, string body) => Show(owner, title, Ui.Text(body, 14, Palette.Body), L("知道了"), danger: false, null, single: true);
+
/// A one-line answer: the new text (maybe empty), or null when cancelled.
public static string? Prompt(Window owner, string title, string value, string? hint, string ok)
{
@@ -27,7 +30,7 @@ static class Dialogs
return Show(owner, title, content, ok, danger: false, box);
}
- static string? Show(Window owner, string title, FrameworkElement content, string ok, bool danger, TextBox? field)
+ static string? Show(Window owner, string title, FrameworkElement content, string ok, bool danger, TextBox? field, bool single = false)
{
string? result = null;
var dialog = new Window
@@ -45,7 +48,8 @@ static class Dialogs
buttons.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(8) });
buttons.ColumnDefinitions.Add(new ColumnDefinition());
Grid.SetColumn(cancel, 2);
- buttons.Children.Add(primary); buttons.Children.Add(cancel);
+ buttons.Children.Add(primary);
+ if (single) { primary.IsCancel = true; Grid.SetColumnSpan(primary, 3); } else buttons.Children.Add(cancel);
var heading = Ui.Text(title, 20, Palette.Ink, FontWeights.SemiBold);
content.Margin = new Thickness(0, 12, 0, 0);
dialog.Content = new Border
diff --git a/windows/src/Cicada/MainWindow.cs b/windows/src/Cicada/MainWindow.cs
index 7e35850..e73b641 100644
--- a/windows/src/Cicada/MainWindow.cs
+++ b/windows/src/Cicada/MainWindow.cs
@@ -279,7 +279,7 @@ sealed class MainWindow : Window
FrameworkElement? target = null;
// The line nearest the topic's time (older notes may hold a time no line has).
var nearest = jumpTo is { } t0 && s.Lines.Count > 0 ? s.Lines.MinBy(l => Math.Abs(l.T - t0)) : null;
- foreach (var l in s.Lines)
+ foreach (var l in s.Lines.OrderBy(x => x.T))
{
var line = NotesWindow.TranscriptRow(l);
if (ReferenceEquals(l, nearest)) target = line;
diff --git a/windows/src/Cicada/NotesWindow.cs b/windows/src/Cicada/NotesWindow.cs
index 4553cef..5d54777 100644
--- a/windows/src/Cicada/NotesWindow.cs
+++ b/windows/src/Cicada/NotesWindow.cs
@@ -244,7 +244,8 @@ sealed class NotesWindow : Window
}
else
{
- stack.Children.Add(Ui.Text($"{Ui.SpokenName(line.SrcLang)} · {Languages.Clock(line.T)}", 12, Palette.Tertiary, wrap: false));
+ var who = line.Speaker == "me" ? L("你") : Ui.SpokenName(line.SrcLang);
+ stack.Children.Add(Ui.Text($"{who} · {Languages.Clock(line.T)}", 12, line.Speaker == "me" ? Palette.AccentText : Palette.Tertiary, wrap: false));
if (line.Dst is not null && line.Dst != line.Src) stack.Children.Add(Gap(Ui.Text(line.Src, 13, Palette.Secondary), 4, top: true));
stack.Children.Add(Gap(Ui.Text(line.Dst ?? line.Src, 17, Palette.Ink, FontWeights.SemiBold), 2, top: true));
if (listen.Listening && listen.Pending > 0)
@@ -315,7 +316,9 @@ sealed class NotesWindow : Window
{
var lines = app.Listen.SessionId is { } id ? app.Store.Get(id)?.Lines ?? [] : [];
var body = new StackPanel();
- foreach (var l in lines) body.Children.Add(TranscriptRow(l));
+ // Stored as they arrive (the notes count them); shown in time order, so a sentence I said
+ // sits between the other side's, which come back from Ming a little later.
+ foreach (var l in lines.OrderBy(x => x.T)) body.Children.Add(TranscriptRow(l));
return body;
}
@@ -327,6 +330,8 @@ sealed class NotesWindow : Window
DockPanel.SetDock(time, Dock.Left);
row.Children.Add(time);
var text = new StackPanel();
+ // What I said into the meeting (同声传译) is marked, as the Mac names it 你.
+ if (l.Speaker == "me") text.Children.Add(Ui.Text(L("你"), 12, Palette.AccentText, FontWeights.SemiBold, wrap: false));
text.Children.Add(Ui.Text(l.Src, 14, Palette.Ink));
if (!string.IsNullOrEmpty(l.Dst) && l.Dst != l.Src) text.Children.Add(Gap(Ui.Text(l.Dst, 13, Palette.Secondary), 2, top: true));
row.Children.Add(text);
diff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.cs
index e93d92e..2adacc8 100644
--- a/windows/src/Cicada/SettingsWindow.cs
+++ b/windows/src/Cicada/SettingsWindow.cs
@@ -60,6 +60,7 @@ sealed class SettingsWindow : Window
Card(Icons.Subtitles, L("听的时候显示"), null, Ui.Segmented([("notes", L("纪要")), ("subtitles", L("字幕条"))], app.Settings.View, app.SetView)),
Card(null, L("字幕文字大小"), null, size),
Card(Icons.Keyboard, L("开始或结束"), app.HotkeyRegistered ? L("在任何程序里都能按") : L("这个快捷键被别的程序占用了"), Keys(Hotkey.Label))));
+ Section(page, "speak", L("同声传译"), SpeakCards());
Section(page, "privacy", L("隐私与启动"), Group(
Card(Icons.Eye, L("共享屏幕时让对方看到"), L("关着时,截图和屏幕共享里看不到纪要和字幕"), Ui.Switch(app.Settings.ShowInCapture, app.SetShowInCapture, L("共享屏幕时让对方看到"))),
Card(Icons.Power, L("开机时启动知了"), null, Ui.Switch(AutoStart.Enabled, v => AutoStart.Enabled = v, L("开机时启动知了"))),
@@ -77,7 +78,7 @@ sealed class SettingsWindow : Window
(string id, string icon, string label)[] items =
[
("ling", Icons.Key, L("Ling")), ("lang", Icons.Globe, L("语言")), ("listen", Icons.Wave, L("听的时候")),
- ("privacy", Icons.Shield, L("隐私与启动")), ("about", Icons.Info, L("关于")),
+ ("speak", Icons.Mic, L("同声传译")), ("privacy", Icons.Shield, L("隐私与启动")), ("about", Icons.Info, L("关于")),
];
foreach (var (id, icon, label) in items)
{
@@ -155,6 +156,49 @@ sealed class SettingsWindow : Window
return dock;
}
+ string? cableProgress;
+
+ /// 同声传译: the switch, the virtual mic, the two languages and the room's voice.
+ FrameworkElement SpeakCards()
+ {
+ var s = app.Settings;
+ var cable = Endpoints.Cable() is not null;
+ FrameworkElement cableControl = cable
+ ? Ui.Row(6, new System.Windows.Controls.Grid { Width = 16, Height = 16, Children = { new System.Windows.Shapes.Ellipse { Fill = Palette.Success }, Ui.Icon(Icons.Check, 16, Brushes.White, stroke: 2) } }, Ui.Text(L("已装好"), 13, Palette.Success, wrap: false))
+ : cableProgress is { } busy ? Ui.Text(busy, 13, Palette.Secondary, wrap: false)
+ : Ui.Button(L("安装"), () => _ = InstallCable(), Ui.Kind.Primary, height: 32);
+ var target = app.Speak.Target;
+ var voices = VoiceCatalog.Options(target, app.WindowsVoice.Has(target)).Select(v => (v.Id, v.Id == VoiceCatalog.SystemId ? L("Windows 自带") : $"{v.Name} · {string.Join(" · ", v.Tags.Split(" · ").Select(L))}")).ToList();
+ var chosen = s.SpeakVoices.TryGetValue(VoiceCatalog.Key(target), out var c) ? c : VoiceCatalog.DefaultId(target, app.Ling.HasKey);
+ var voice = Ui.Row(8,
+ Ui.Choice(voices, chosen, v => { s.SpeakVoices[VoiceCatalog.Key(target)] = v; Save(); }, 280),
+ Ui.Button(L("试听"), () => _ = app.Preview(target), height: 32));
+ var mine = Languages.Sources.FirstOrDefault(x => x.Code == Languages.FromSystem(System.Globalization.CultureInfo.CurrentUICulture.Name))?.Name ?? "";
+ return Group(
+ Card(Icons.Mic, L("同声传译"), LF("按住%@说话,对方听到的是翻译后的声音", PushToTalk.Label), Ui.Switch(s.Speak, v => { s.Speak = v; Save(); }, L("同声传译"))),
+ Card(Icons.Speaker, L("虚拟麦克风"), cable ? L("在会议软件里把麦克风选成 CABLE Output") : L("需要装免费的 VB-Cable;装的时候 Windows 会请你确认"), cableControl),
+ Card(null, L("我说的语言"), null, Ui.Choice([("system", LF("跟随系统(%@)", mine)), .. Languages.Sources.Select(x => (x.Code, x.Name))], s.SpeakFrom, v => { s.SpeakFrom = v; Save(); Render(); })),
+ Card(null, L("对方听到的语言"), s.SpeakTo == "room" ? LF("现在是 %@", Ui.TargetName(target)) : null,
+ Ui.Choice([("room", L("对方说的语言")), .. Languages.Targets.Select(t => (t.Code, t.Name))], s.SpeakTo, v => { s.SpeakTo = v; Save(); Render(); })),
+ Card(null, LF("对方听到的声音(%@)", Ui.TargetName(target)), null, voice));
+ }
+
+ async Task InstallCable()
+ {
+ cableProgress = L("正在下载…"); Render();
+ var result = await CableInstaller.Install(p => Dispatcher.BeginInvoke(() => { cableProgress = p; Render(); }));
+ cableProgress = null;
+ Render();
+ if (result != CableInstaller.Result.Installed)
+ Dialogs.Tell(this, L("虚拟麦克风没装上"), result switch
+ {
+ CableInstaller.Result.DownloadFailed => L("下载失败,检查网络后再试。"),
+ CableInstaller.Result.BadPackage => L("下载到的安装包和预期的不一样,为了安全没有安装。"),
+ CableInstaller.Result.Declined => L("需要你在 Windows 的提示里点“是”才能安装。"),
+ _ => L("安装没有完成,可以重启电脑后再试。"),
+ });
+ }
+
FrameworkElement KeyCard()
{
var state = app.Ling.KeyState;
diff --git a/windows/src/Cicada/SpeakBar.cs b/windows/src/Cicada/SpeakBar.cs
new file mode 100644
index 0000000..b93e20f
--- /dev/null
+++ b/windows/src/Cicada/SpeakBar.cs
@@ -0,0 +1,78 @@
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Windows.Threading;
+using static Cicada.Strings;
+
+namespace Cicada.App;
+
+/// The bar while I speak: 正在听你说 while the key is held, then what I said and what the room
+/// heard, or why nothing went out. Like the notes panel it never takes focus and stays out of
+/// screen captures; it sits above the taskbar (above the subtitle bar when that is showing).
+sealed class SpeakBar : Window
+{
+ readonly Controller app;
+ readonly ContentControl body = new();
+ readonly DispatcherTimer hide = new() { Interval = TimeSpan.FromSeconds(4) };
+
+ public SpeakBar(Controller app)
+ {
+ this.app = app;
+ WindowStyle = WindowStyle.None; Background = Palette.Night; Topmost = true; ShowInTaskbar = false; ShowActivated = false;
+ ResizeMode = ResizeMode.NoResize; SizeToContent = SizeToContent.Height; Width = 560; FontFamily = Palette.Font; Title = L("知了");
+ System.Windows.Shell.WindowChrome.SetWindowChrome(this, new System.Windows.Shell.WindowChrome { CaptionHeight = 0, ResizeBorderThickness = new Thickness(0), GlassFrameThickness = new Thickness(0, 1, 0, 0), UseAeroCaptionButtons = false });
+ SourceInitialized += (_, _) =>
+ {
+ Native.MakeNonActivating(this);
+ Native.UseSystemFrame(this, dark: true);
+ Native.SetCaptureVisible(this, app.Settings.ShowInCapture);
+ };
+ Content = new Border { Padding = new Thickness(18, 12, 18, 14), Child = body };
+ SizeChanged += (_, _) => Place();
+ hide.Tick += (_, _) => { hide.Stop(); Hide(); };
+ }
+
+ void Place()
+ {
+ var area = SystemParameters.WorkArea;
+ Left = area.Left + (area.Width - ActualWidth) / 2;
+ var above = app.Settings.View == "subtitles" && app.NotesVisible ? 150 : 16;
+ Top = area.Bottom - ActualHeight - above;
+ }
+
+ public void Refresh()
+ {
+ var s = app.Speak;
+ hide.Stop();
+ var stack = new StackPanel();
+ switch (s.State)
+ {
+ case SpeakEngine.Phase.Recording:
+ stack.Children.Add(Ui.Row(10, Ui.LiveDot(10), Ui.Text(L("正在听你说 · 松开发送"), 15, Brushes.White, FontWeights.SemiBold, wrap: false)));
+ stack.Children.Add(Gap(Ui.Text(LF("对方会听到%@", Ui.TargetName(s.Target)), 12, Palette.NightText), 4));
+ break;
+ case SpeakEngine.Phase.Translating:
+ stack.Children.Add(Ui.Text(L("正在翻译…"), 15, Brushes.White, FontWeights.SemiBold, wrap: false));
+ break;
+ case SpeakEngine.Phase.Speaking or SpeakEngine.Phase.Idle when s.Heard is not null:
+ if (s.Said is not null) stack.Children.Add(Ui.Text(s.Said, 13, Palette.NightText));
+ stack.Children.Add(Gap(Ui.Text(s.Heard!, 18, Brushes.White, FontWeights.SemiBold), 4));
+ stack.Children.Add(Gap(Ui.Text(s.State == SpeakEngine.Phase.Speaking ? L("正在说给对方听…") : L("对方已听到"), 12, Palette.NightText), 6));
+ if (s.State == SpeakEngine.Phase.Idle) hide.Start();
+ break;
+ case SpeakEngine.Phase.Failed:
+ if (s.Said is not null) stack.Children.Add(Ui.Text(s.Said, 13, Palette.NightText));
+ stack.Children.Add(Gap(Ui.Text(s.Problem ?? L("没翻译成功,没有发出去"), 15, new SolidColorBrush(Color.FromRgb(0xFF, 0x9B, 0x78)), FontWeights.SemiBold), 4));
+ hide.Start();
+ break;
+ default:
+ Hide();
+ return;
+ }
+ body.Content = stack;
+ if (!IsVisible) Show();
+ Place();
+ }
+
+ static FrameworkElement Gap(FrameworkElement e, double top) { e.Margin = new Thickness(0, top, 0, 0); return e; }
+}
diff --git a/windows/src/Cicada/Speaking.cs b/windows/src/Cicada/Speaking.cs
new file mode 100644
index 0000000..ec75920
--- /dev/null
+++ b/windows/src/Cicada/Speaking.cs
@@ -0,0 +1,156 @@
+using System.Diagnostics;
+using System.IO.Compression;
+using System.Net.Http;
+using System.Runtime.InteropServices;
+
+namespace Cicada.App;
+
+/// Windows' own voice (OneCore), for when Ming's can't speak: always there, no key needed.
+sealed class WindowsVoice : ISystemVoice
+{
+ public async Task<(byte[] pcm, int rate)?> Speak(string text, string language)
+ {
+ try
+ {
+ using var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
+ var head = VoiceCatalog.Key(language);
+ var voice = Windows.Media.SpeechSynthesis.SpeechSynthesizer.AllVoices
+ .Where(v => v.Language.StartsWith(language, StringComparison.OrdinalIgnoreCase) || v.Language.StartsWith(head, StringComparison.OrdinalIgnoreCase))
+ .OrderByDescending(v => v.Language.Equals(language, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
+ // No voice for the language: say nothing rather than read it in another language's voice.
+ if (voice is null) { Log.Debug($"windows voice: none for {language}"); return null; }
+ synth.Voice = voice;
+ using var stream = await synth.SynthesizeTextToStreamAsync(text);
+ var bytes = new byte[stream.Size];
+ using (var reader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0)))
+ {
+ await reader.LoadAsync((uint)stream.Size);
+ reader.ReadBytes(bytes);
+ }
+ return Pcm(bytes);
+ }
+ catch (Exception e) { Log.Debug($"windows voice: failed {e.GetType().Name}"); return null; }
+ }
+
+ public bool Has(string language)
+ {
+ try
+ {
+ var head = VoiceCatalog.Key(language);
+ return Windows.Media.SpeechSynthesis.SpeechSynthesizer.AllVoices.Any(v => v.Language.StartsWith(head, StringComparison.OrdinalIgnoreCase));
+ }
+ catch { return false; }
+ }
+
+ /// The PCM inside a 16-bit WAV, mixed to mono, at its own rate.
+ static (byte[], int)? Pcm(byte[] wav)
+ {
+ if (wav.Length < 44) return null;
+ int i = 12, channels = 1, rate = 16000;
+ while (i + 8 <= wav.Length)
+ {
+ var id = System.Text.Encoding.ASCII.GetString(wav, i, 4);
+ int size = BitConverter.ToInt32(wav, i + 4);
+ if (id == "fmt ") { channels = BitConverter.ToInt16(wav, i + 10); rate = BitConverter.ToInt32(wav, i + 12); }
+ else if (id == "data")
+ {
+ size = Math.Min(size, wav.Length - i - 8);
+ int frames = size / 2 / channels;
+ var mono = new byte[frames * 2];
+ for (int f = 0; f < frames; f++)
+ {
+ int sum = 0;
+ for (int c = 0; c < channels; c++) sum += BitConverter.ToInt16(wav, i + 8 + (f * channels + c) * 2);
+ BitConverter.GetBytes((short)(sum / channels)).CopyTo(mono, f * 2);
+ }
+ return (mono, rate);
+ }
+ i += 8 + size + (size & 1);
+ }
+ return null;
+ }
+}
+
+/// Hold right Ctrl to talk, anywhere. RegisterHotKey can't see a key being let go, so this is a
+/// low-level keyboard hook; it only watches right Ctrl and never swallows it. (Right Alt is AltGr
+/// on many keyboards, and a lone Alt opens app menus when released.)
+sealed class PushToTalk : IDisposable
+{
+ public static string Label => Strings.L("右 Ctrl");
+ const int WhKeyboardLl = 13, WmKeyDown = 0x100, WmKeyUp = 0x101, WmSysKeyDown = 0x104, WmSysKeyUp = 0x105, VkRControl = 0xA3;
+ readonly HookProc proc; // held, or the GC collects it and Windows calls freed memory
+ readonly IntPtr hook;
+ bool down;
+ public event Action? Pressed, Released;
+
+ public PushToTalk()
+ {
+ proc = Hook;
+ hook = SetWindowsHookEx(WhKeyboardLl, proc, GetModuleHandle(null), 0);
+ Log.Debug($"push to talk: {(hook == IntPtr.Zero ? "hook failed" : "ready")}");
+ }
+
+ IntPtr Hook(int code, IntPtr wParam, IntPtr lParam)
+ {
+ if (code >= 0 && Marshal.ReadInt32(lParam) == VkRControl)
+ {
+ var msg = wParam.ToInt32();
+ if ((msg == WmKeyDown || msg == WmSysKeyDown) && !down) { down = true; Pressed?.Invoke(); }
+ else if ((msg == WmKeyUp || msg == WmSysKeyUp) && down) { down = false; Released?.Invoke(); }
+ }
+ return CallNextHookEx(hook, code, wParam, lParam);
+ }
+
+ public void Dispose() { if (hook != IntPtr.Zero) UnhookWindowsHookEx(hook); }
+
+ delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);
+ [DllImport("user32.dll", SetLastError = true)] static extern IntPtr SetWindowsHookEx(int id, HookProc proc, IntPtr module, uint thread);
+ [DllImport("user32.dll")] static extern bool UnhookWindowsHookEx(IntPtr hook);
+ [DllImport("user32.dll")] static extern IntPtr CallNextHookEx(IntPtr hook, int code, IntPtr wParam, IntPtr lParam);
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern IntPtr GetModuleHandle(string? name);
+}
+
+/// Installs VB-Cable: VB-Audio's own package, downloaded when the user asks, checked against the
+/// pinned SHA-256 before anything runs, then its installer with Windows' admin prompt.
+static class CableInstaller
+{
+ public enum Result { Installed, DownloadFailed, BadPackage, Declined, Failed }
+
+ public static async Task<Result> Install(Action<string> progress)
+ {
+ progress(Strings.L("正在下载…"));
+ byte[] zip;
+ try
+ {
+ using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(3) };
+ zip = await http.GetByteArrayAsync(VirtualCable.PackageUrl);
+ }
+ catch (Exception e) { Log.Debug($"cable: download failed {e.GetType().Name}"); return Result.DownloadFailed; }
+ if (!VirtualCable.Verify(zip)) { Log.Debug("cable: package hash mismatch, not run"); return Result.BadPackage; }
+ var dir = Path.Combine(Path.GetTempPath(), "cicada-vbcable");
+ try
+ {
+ if (Directory.Exists(dir)) Directory.Delete(dir, true);
+ using (var ms = new MemoryStream(zip)) ZipFile.ExtractToDirectory(ms, dir);
+ }
+ catch (Exception e) { Log.Debug($"cable: extract failed {e.GetType().Name}"); return Result.Failed; }
+ progress(Strings.L("正在安装…"));
+ // The x64 installer also puts the ARM64 driver on Windows on ARM.
+ var setup = Path.Combine(dir, Environment.Is64BitOperatingSystem ? "VBCABLE_Setup_x64.exe" : "VBCABLE_Setup.exe");
+ try
+ {
+ using var p = Process.Start(new ProcessStartInfo(setup, "-i -h") { UseShellExecute = true, Verb = "runas", WorkingDirectory = dir });
+ if (p is null) return Result.Failed;
+ await p.WaitForExitAsync();
+ Log.Debug($"cable: setup exited {p.ExitCode}");
+ }
+ catch (System.ComponentModel.Win32Exception e) when (e.NativeErrorCode == 1223) { return Result.Declined; }
+ catch (Exception e) { Log.Debug($"cable: setup failed {e.GetType().Name}"); return Result.Failed; }
+ for (int i = 0; i < 40; i++)
+ {
+ if (Endpoints.Cable() is not null) { Log.Debug("cable: endpoint ready"); return Result.Installed; }
+ await Task.Delay(500);
+ }
+ return Result.Failed;
+ }
+}
diff --git a/windows/src/Cicada/Strings/en.lproj/Windows.strings b/windows/src/Cicada/Strings/en.lproj/Windows.strings
index fefa498..f59bd48 100644
--- a/windows/src/Cicada/Strings/en.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/en.lproj/Windows.strings
@@ -10,9 +10,13 @@
"Ling 太忙" = "Ling is busy";
"M月d日" = "MMM d";
"M月d日 HH:mm" = "MMM d HH:mm";
+"Windows 不让知了用麦克风:设置 › 隐私和安全性 › 麦克风" = "Windows blocked microphone access for Cicada: Settings › Privacy & security › Microphone";
"Windows 没能把这个窗口从屏幕共享里藏起来,对方可能看得到。" = "Windows couldn't hide this window from screen sharing. Others might see it.";
+"Windows 自带" = "Built into Windows";
"yyyy年M月d日" = "MMM d, yyyy";
"“%@”的纪要和文字记录都会删掉,没法恢复。" = "The notes and transcript for \"%@\" will be permanently deleted.";
+"下载到的安装包和预期的不一样,为了安全没有安装。" = "The downloaded installer didn't match what we expected, so it wasn't installed for your safety.";
+"下载失败,检查网络后再试。" = "Download failed. Check your connection and try again.";
"之后每 45 秒更新一次" = "Updated every 45 seconds after that";
"会议" = "Meeting";
"会议记录存放位置" = "Meeting records folder";
@@ -25,26 +29,37 @@
"只加密存在这台电脑上,只发给 Ling" = "Encrypted on this PC and sent only to Ling";
"可以用" = "Key works";
"可以用 · 只加密存在这台电脑上" = "Working · Encrypted on this PC only";
+"右 Ctrl" = "Right Ctrl";
"听到了" = "Audio detected";
"听电脑播放的声音,不用麦克风" = "Listens to your PC's audio, not your mic";
"听的时候" = "While listening";
"和 Mac 版格式相同" = "Uses the same format as Cicada for Mac";
"和字幕一样" = "Same as subtitles";
"在任何程序里都能按" = "Works in any app";
+"在会议软件里把麦克风选成 CABLE Output" = "In your meeting app, set the microphone to CABLE Output";
"在听下一句" = "Listening for next line";
"填写" = "Add";
"字幕文字大小" = "Subtitle text size";
+"安装没有完成,可以重启电脑后再试。" = "Installation didn't finish. Restart your PC and try again.";
+"对方会听到%@" = "Others will hear %@";
"对方可见" = "Visible to others";
+"对方听到的声音(%@)" = "Voice others hear (%@)";
+"对方听到的语言" = "Language others hear";
+"对方已听到" = "Sent to meeting";
"就绪 · Ling 已连接" = "Ready · Connected to Ling";
"屏幕共享里看不到" = "Hidden from screen sharing";
+"已装好" = "Installed";
"开" = "On";
"开会时点任务栏里的知了图标,或按 %@ 开始。" = "When a meeting starts, select the Cicada icon in the taskbar or press %@.";
"开始或结束" = "Start or stop listening";
"开机时启动知了" = "Start Cicada when I sign in";
"开机时启动知了(在任务栏右下角待命)" = "Start Cicada when I sign in (waits in the system tray)";
"待办 %@" = "Action items: %@";
+"我说的语言" = "Language I speak";
"打开文件夹" = "Open folder";
"打开设置" = "Settings";
+"按住%@说话" = "Hold %@ to speak";
+"按住%@说话,对方听到的是翻译后的声音" = "Hold %@ to speak. Others hear the translated voice.";
"换成字幕条" = "Switch to subtitle bar";
"换成纪要" = "Switch to notes";
"换成耳机或蓝牙音箱也能接着听。" = "Keeps working when you switch to headphones or Bluetooth speakers.";
@@ -61,19 +76,28 @@
"术语" = "Terms";
"查看全部" = "See all";
"查看记录" = "Meeting records";
+"正在听你说 · 松开发送" = "Listening · Release to send";
"正在听:%@" = "Listening to: %@";
+"正在说给对方听…" = "Speaking to others…";
+"没听到你说话,没有发出去" = "Didn't hear anything. Nothing was sent.";
+"没听清,没有发出去" = "Couldn't catch that. Nothing was sent.";
+"没找到麦克风" = "No microphone found";
"没有声音?先确认电脑没静音" = "No sound? Make sure your PC isn't muted.";
"没有找到" = "No results found";
+"没翻译成功,没有发出去" = "Couldn't translate. Nothing was sent.";
+"没能发出声音" = "Couldn't play audio";
"清空就用纪要起的名字:%@" = "Leave blank to use the title from notes: %@";
"点“开始听”,电脑里播放的声音会变成双语字幕和纪要" = "Select \"Start listening\" to turn your PC's audio into live bilingual subtitles and meeting notes.";
"点任务栏右下角的知了图标再打开纪要。" = "Select the Cicada icon in the system tray to reopen notes.";
"点任务栏里的知了图标,开始听第一场会。" = "Select the Cicada icon in the taskbar to start your first meeting.";
+"现在是 %@" = "Currently %@";
"电脑里一有人声,字幕就出来" = "Subtitles will appear as soon as someone speaks";
"界面语言" = "App language";
"知了 %@" = "Cicada %@";
"知了听的是电脑播放出来的声音,不用麦克风,也不用授权。放一段视频或音乐试试。" = "Cicada listens to what your PC plays—no mic or permissions needed. Play a video or song to test it.";
"知了还在听" = "Cicada is still listening";
"知了需要 Windows 10 2004 或更新的版本。" = "Cicada requires Windows 10 version 2004 or later.";
+"知道了" = "Got it";
"稍后会自动重试。" = "We'll try again automatically in a moment.";
"等有人说话" = "Waiting for speech";
"系统声音" = "System audio";
@@ -81,6 +105,7 @@
"纪要停留在 %@。" = "Notes stop at %@.";
"纪要和翻译用的模型" = "Model for notes and translation";
"纪要整理好了" = "Meeting notes are ready";
+"虚拟麦克风没装上" = "Couldn't install the virtual microphone";
"要粘贴 sk- 开头的那串" = "Paste a key that starts with sk-";
"设置知了" = "Set up Cicada";
"识别、翻译和纪要都靠它。到 Ling 开放平台点“创建令牌”,复制 sk- 开头的那串,粘贴到下面。" = "Cicada uses Ling for transcription, translation, and notes. Go to the Ling platform, select \"Create token\", and paste the key starting with sk- below.";
@@ -89,11 +114,18 @@
"还没填 key" = "No key added";
"还没接上 Ling" = "Not connected to Ling";
"还没有会议记录" = "No meeting records yet";
+"还没装虚拟麦克风,去设置里装一下" = "Virtual microphone isn't installed. Install it in Settings.";
"这个 key 不能用,检查是否复制完整,或重新创建一个" = "This key didn't work. Make sure you copied the whole key, or create a new one.";
"这个快捷键被别的程序占用了" = "This shortcut is already in use by another app";
+"这台电脑没有这种语言的声音,没有发出去" = "This PC doesn't have a voice for this language. Nothing was sent.";
"这段时间的话没能识别。检查网络后点重试。" = "Some audio couldn't be transcribed. Check your network and try again.";
"连不上 Ling" = "Can't connect to Ling";
"连不上 Ling,检查网络" = "Can't connect to Ling. Check your network.";
+"连不上 Ling,没有发出去" = "Couldn't connect to Ling. Nothing was sent.";
"重命名" = "Rename";
"重新打开知了后生效" = "Takes effect after you restart Cicada";
"隐私与启动" = "Privacy & startup";
+"需要 Ling key 才能说" = "A Ling key is needed to speak";
+"需要你在 Windows 的提示里点“是”才能安装。" = "Select Yes in the Windows prompt to install.";
+"需要装免费的 VB-Cable;装的时候 Windows 会请你确认" = "Requires the free VB-Cable driver. Windows will ask you to confirm.";
+"麦克风打不开" = "Couldn't open the microphone";
diff --git a/windows/src/Cicada/Strings/ja.lproj/Windows.strings b/windows/src/Cicada/Strings/ja.lproj/Windows.strings
index 61d45b3..0b00934 100644
--- a/windows/src/Cicada/Strings/ja.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/ja.lproj/Windows.strings
@@ -10,9 +10,13 @@
"Ling 太忙" = "Ling が混雑しています";
"M月d日" = "M月d日";
"M月d日 HH:mm" = "M月d日 HH:mm";
+"Windows 不让知了用麦克风:设置 › 隐私和安全性 › 麦克风" = "Windows で Cicada のマイクがオフになっています:設定 › プライバシーとセキュリティ › マイク";
"Windows 没能把这个窗口从屏幕共享里藏起来,对方可能看得到。" = "Windows でこのウィンドウを画面共有から隠せませんでした。相手に見える可能性があります。";
+"Windows 自带" = "Windows 標準";
"yyyy年M月d日" = "yyyy年M月d日";
"“%@”的纪要和文字记录都会删掉,没法恢复。" = "「%@」のメモと文字起こしが削除されます。元に戻すことはできません。";
+"下载到的安装包和预期的不一样,为了安全没有安装。" = "ダウンロードしたインストーラーが想定と異なるため、安全のためインストールを中止しました。";
+"下载失败,检查网络后再试。" = "ダウンロードできませんでした。ネットワークを確認してもう一度お試しください。";
"之后每 45 秒更新一次" = "その後は 45 秒ごとに更新されます";
"会议" = "会議";
"会议记录存放位置" = "会議の記録の保存先";
@@ -25,26 +29,37 @@
"只加密存在这台电脑上,只发给 Ling" = "暗号化してこの PC にのみ保存され、Ling 以外に送信されません";
"可以用" = "使用できます";
"可以用 · 只加密存在这台电脑上" = "使用可能 · 暗号化してこの PC にのみ保存";
+"右 Ctrl" = "右 Ctrl";
"听到了" = "音声を確認できました";
"听电脑播放的声音,不用麦克风" = "マイクではなく、PC で再生中の音声を聞き取ります";
"听的时候" = "聞き取り中";
"和 Mac 版格式相同" = "Mac 版と同じ形式です";
"和字幕一样" = "字幕と同じ";
"在任何程序里都能按" = "どのアプリを使っていても押せます";
+"在会议软件里把麦克风选成 CABLE Output" = "会議アプリでマイクを「CABLE Output」に設定してください";
"在听下一句" = "次の文を聞き取り中";
"填写" = "入力";
"字幕文字大小" = "字幕の文字サイズ";
+"安装没有完成,可以重启电脑后再试。" = "インストールが完了しませんでした。PC を再起動してからもう一度お試しください。";
+"对方会听到%@" = "相手には%@で聞こえます";
"对方可见" = "相手に表示中";
+"对方听到的声音(%@)" = "相手に聞こえる声(%@)";
+"对方听到的语言" = "相手に聞こえる言語";
+"对方已听到" = "相手に届きました";
"就绪 · Ling 已连接" = "準備完了 · Ling 接続済み";
"屏幕共享里看不到" = "画面共有には映りません";
+"已装好" = "インストール済み";
"开" = "オン";
"开会时点任务栏里的知了图标,或按 %@ 开始。" = "会議が始まったら、タスクバーの Cicada アイコンをクリックするか、%@ キーを押して開始します。";
"开始或结束" = "聞き取りの開始 / 終了";
"开机时启动知了" = "PC 起動時に Cicada を起動する";
"开机时启动知了(在任务栏右下角待命)" = "PC 起動時に Cicada を起動する(タスクバー右下に常駐)";
"待办 %@" = "ToDo %@";
+"我说的语言" = "自分が話す言語";
"打开文件夹" = "フォルダーを開く";
"打开设置" = "設定";
+"按住%@说话" = "%@ を押しながら話す";
+"按住%@说话,对方听到的是翻译后的声音" = "%@ を押しながら話すと、相手には翻訳された声が届きます";
"换成字幕条" = "字幕バーに切り替え";
"换成纪要" = "メモに切り替え";
"换成耳机或蓝牙音箱也能接着听。" = "イヤホンや Bluetooth スピーカーに切り替えてもそのまま聞き取れます。";
@@ -61,19 +76,28 @@
"术语" = "用語";
"查看全部" = "すべて表示";
"查看记录" = "会議の記録";
+"正在听你说 · 松开发送" = "聞き取り中 · 離して送信";
"正在听:%@" = "聞き取り中:%@";
+"正在说给对方听…" = "相手に読み上げています…";
+"没听到你说话,没有发出去" = "声が聞き取れなかったため、送信されませんでした";
+"没听清,没有发出去" = "うまく聞き取れなかったため、送信されませんでした";
+"没找到麦克风" = "マイクが見つかりません";
"没有声音?先确认电脑没静音" = "音が聞こえない場合は、PC がミュートになっていないか確認してください";
"没有找到" = "見つかりませんでした";
+"没翻译成功,没有发出去" = "翻訳できなかったため、送信されませんでした";
+"没能发出声音" = "音声を出力できませんでした";
"清空就用纪要起的名字:%@" = "空欄にするとメモのタイトルが使われます:%@";
"点“开始听”,电脑里播放的声音会变成双语字幕和纪要" = "「聞き取り開始」をクリックすると、PC で再生中の音声が 2 か国語の字幕とメモになります。";
"点任务栏右下角的知了图标再打开纪要。" = "タスクバー右下の Cicada アイコンをクリックすると、メモを再度開けます。";
"点任务栏里的知了图标,开始听第一场会。" = "タスクバーの Cicada アイコンをクリックして、最初の会議を聞き取りましょう。";
+"现在是 %@" = "現在:%@";
"电脑里一有人声,字幕就出来" = "声が聞こえるとすぐに字幕が表示されます";
"界面语言" = "表示言語";
"知了 %@" = "Cicada %@";
"知了听的是电脑播放出来的声音,不用麦克风,也不用授权。放一段视频或音乐试试。" = "Cicada は PC で再生される音声を聞き取ります。マイクも権限の許可も不要です。動画や音楽を再生して試してみましょう。";
"知了还在听" = "Cicada は聞き取りを続けています";
"知了需要 Windows 10 2004 或更新的版本。" = "Cicada には Windows 10 バージョン 2004 以降が必要です。";
+"知道了" = "OK";
"稍后会自动重试。" = "しばらくすると自動的に再試行します。";
"等有人说话" = "音声を待っています";
"系统声音" = "システム音声";
@@ -81,6 +105,7 @@
"纪要停留在 %@。" = "メモは %@ までです。";
"纪要和翻译用的模型" = "メモと翻訳に使用するモデル";
"纪要整理好了" = "メモがまとまりました";
+"虚拟麦克风没装上" = "仮想マイクをインストールできませんでした";
"要粘贴 sk- 开头的那串" = "sk- で始まる文字列を貼り付けてください";
"设置知了" = "Cicada のセットアップ";
"识别、翻译和纪要都靠它。到 Ling 开放平台点“创建令牌”,复制 sk- 开头的那串,粘贴到下面。" = "音声認識、翻訳、メモの作成には Ling を使用します。Ling プラットフォームで「トークンを作成」をクリックし、sk- で始まる文字列を下に貼り付けてください。";
@@ -89,11 +114,18 @@
"还没填 key" = "キーが未入力です";
"还没接上 Ling" = "Ling に未接続";
"还没有会议记录" = "会議の記録はまだありません";
+"还没装虚拟麦克风,去设置里装一下" = "仮想マイクがまだありません。設定からインストールしてください";
"这个 key 不能用,检查是否复制完整,或重新创建一个" = "このキーは使用できません。最後までコピーされているか確認するか、新しく作成してください。";
"这个快捷键被别的程序占用了" = "このショートカットは他のアプリで使用されています";
+"这台电脑没有这种语言的声音,没有发出去" = "この PC にはこの言語の音声がないため、送信されませんでした";
"这段时间的话没能识别。检查网络后点重试。" = "この間の音声を認識できませんでした。ネットワークを確認して再試行してください。";
"连不上 Ling" = "Ling に接続できません";
"连不上 Ling,检查网络" = "Ling に接続できません。ネットワークを確認してください。";
+"连不上 Ling,没有发出去" = "Ling に接続できなかったため、送信されませんでした";
"重命名" = "名前を変更";
"重新打开知了后生效" = "Cicada の再起動後に反映されます";
"隐私与启动" = "プライバシーと起動";
+"需要 Ling key 才能说" = "話すには Ling キーが必要です";
+"需要你在 Windows 的提示里点“是”才能安装。" = "インストールするには、Windows の確認画面で「はい」を選んでください。";
+"需要装免费的 VB-Cable;装的时候 Windows 会请你确认" = "無料の VB-Cable が必要です。インストール時に Windows の確認画面が出ます";
+"麦克风打不开" = "マイクを開けません";
diff --git a/windows/src/Cicada/Strings/ko.lproj/Windows.strings b/windows/src/Cicada/Strings/ko.lproj/Windows.strings
index b3d89af..01208f5 100644
--- a/windows/src/Cicada/Strings/ko.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/ko.lproj/Windows.strings
@@ -10,9 +10,13 @@
"Ling 太忙" = "Ling 사용량 많음";
"M月d日" = "M월 d일";
"M月d日 HH:mm" = "M월 d일 HH:mm";
+"Windows 不让知了用麦克风:设置 › 隐私和安全性 › 麦克风" = "Windows에서 Cicada의 마이크 접근을 막았습니다: 설정 › 개인 정보 및 보안 › 마이크";
"Windows 没能把这个窗口从屏幕共享里藏起来,对方可能看得到。" = "Windows에서 이 창을 화면 공유에서 숨기지 못했습니다. 상대방에게 보일 수 있습니다.";
+"Windows 自带" = "Windows 기본 제공";
"yyyy年M月d日" = "yyyy년 M월 d일";
"“%@”的纪要和文字记录都会删掉,没法恢复。" = "'%@'의 회의록과 대화 기록이 모두 삭제되며 복구할 수 없습니다.";
+"下载到的安装包和预期的不一样,为了安全没有安装。" = "다운로드한 설치 파일이 예상과 달라 안전을 위해 설치하지 않았습니다.";
+"下载失败,检查网络后再试。" = "다운로드하지 못했습니다. 네트워크를 확인한 후 다시 시도해 주세요.";
"之后每 45 秒更新一次" = "이후 45초마다 업데이트됩니다";
"会议" = "회의";
"会议记录存放位置" = "회의 기록 저장 위치";
@@ -25,26 +29,37 @@
"只加密存在这台电脑上,只发给 Ling" = "암호화되어 이 PC에만 저장되며 Ling으로만 전송됩니다";
"可以用" = "사용 가능";
"可以用 · 只加密存在这台电脑上" = "사용 가능 · 암호화되어 이 PC에만 저장됨";
+"右 Ctrl" = "오른쪽 Ctrl";
"听到了" = "소리가 감지됨";
"听电脑播放的声音,不用麦克风" = "마이크가 아닌 PC에서 재생되는 소리를 듣습니다";
"听的时候" = "듣는 동안";
"和 Mac 版格式相同" = "Mac 버전과 동일한 형식입니다";
"和字幕一样" = "자막과 동일";
"在任何程序里都能按" = "어떤 프로그램에서든 누를 수 있습니다";
+"在会议软件里把麦克风选成 CABLE Output" = "회의 앱에서 마이크를 CABLE Output으로 선택하세요";
"在听下一句" = "다음 문장 듣는 중";
"填写" = "입력";
"字幕文字大小" = "자막 글자 크기";
+"安装没有完成,可以重启电脑后再试。" = "설치가 완료되지 않았습니다. PC를 다시 시작한 후 다시 시도해 보세요.";
+"对方会听到%@" = "상대방에게 %@(으)로 들립니다";
"对方可见" = "상대방에게 보임";
+"对方听到的声音(%@)" = "상대방에게 들리는 목소리(%@)";
+"对方听到的语言" = "상대방에게 들리는 언어";
+"对方已听到" = "상대방에게 전달됨";
"就绪 · Ling 已连接" = "준비됨 · Ling 연결됨";
"屏幕共享里看不到" = "화면 공유에 표시되지 않음";
+"已装好" = "설치됨";
"开" = "켬";
"开会时点任务栏里的知了图标,或按 %@ 开始。" = "회의할 때 작업 표시줄의 Cicada 아이콘을 클릭하거나 %@ 키를 눌러 시작하세요.";
"开始或结束" = "듣기 시작 또는 종료";
"开机时启动知了" = "시작할 때 Cicada 실행";
"开机时启动知了(在任务栏右下角待命)" = "시작할 때 Cicada 실행(작업 표시줄 오른쪽 아래에 대기)";
"待办 %@" = "할 일 %@";
+"我说的语言" = "내가 말하는 언어";
"打开文件夹" = "폴더 열기";
"打开设置" = "설정";
+"按住%@说话" = "%@ 키를 누른 채 말하기";
+"按住%@说话,对方听到的是翻译后的声音" = "%@ 키를 누른 채 말하면 상대방에게는 번역된 목소리가 들립니다";
"换成字幕条" = "자막 바로 전환";
"换成纪要" = "회의록으로 전환";
"换成耳机或蓝牙音箱也能接着听。" = "이어폰이나 블루투스 스피커로 바꿔도 계속 들을 수 있습니다.";
@@ -61,19 +76,28 @@
"术语" = "용어";
"查看全部" = "모두 보기";
"查看记录" = "회의 기록";
+"正在听你说 · 松开发送" = "듣는 중 · 키를 놓으면 전송";
"正在听:%@" = "듣는 중인 기기: %@";
+"正在说给对方听…" = "상대방에게 말하는 중…";
+"没听到你说话,没有发出去" = "목소리가 들리지 않아 전송하지 않았습니다";
+"没听清,没有发出去" = "잘 알아듣지 못해 전송하지 않았습니다";
+"没找到麦克风" = "마이크를 찾을 수 없습니다";
"没有声音?先确认电脑没静音" = "소리가 안 나나요? 먼저 PC가 음소거 상태인지 확인하세요";
"没有找到" = "결과 없음";
+"没翻译成功,没有发出去" = "번역하지 못해 전송하지 않았습니다";
+"没能发出声音" = "소리를 재생하지 못했습니다";
"清空就用纪要起的名字:%@" = "비워 두면 회의록에서 생성된 제목을 사용합니다: %@";
"点“开始听”,电脑里播放的声音会变成双语字幕和纪要" = "'듣기 시작'을 클릭하면 PC에서 재생되는 소리가 실시간 이중 언어 자막과 회의록으로 변환됩니다.";
"点任务栏右下角的知了图标再打开纪要。" = "작업 표시줄 오른쪽 아래의 Cicada 아이콘을 클릭하면 회의록을 다시 열 수 있습니다.";
"点任务栏里的知了图标,开始听第一场会。" = "작업 표시줄의 Cicada 아이콘을 클릭해 첫 회의를 기록해 보세요.";
+"现在是 %@" = "현재: %@";
"电脑里一有人声,字幕就出来" = "소리가 감지되면 바로 자막이 나타납니다";
"界面语言" = "앱 표시 언어";
"知了 %@" = "Cicada %@";
"知了听的是电脑播放出来的声音,不用麦克风,也不用授权。放一段视频或音乐试试。" = "Cicada는 마이크나 별도 권한 없이 PC에서 재생되는 소리를 듣습니다. 동영상이나 음악을 재생해 테스트해 보세요.";
"知了还在听" = "Cicada가 계속 듣고 있습니다";
"知了需要 Windows 10 2004 或更新的版本。" = "Cicada를 사용하려면 Windows 10 버전 2004 이상이 필요합니다.";
+"知道了" = "확인";
"稍后会自动重试。" = "잠시 후 자동으로 다시 시도합니다.";
"等有人说话" = "음성 대기 중";
"系统声音" = "시스템 소리";
@@ -81,6 +105,7 @@
"纪要停留在 %@。" = "노트는 %@에서 멈춰 있습니다.";
"纪要和翻译用的模型" = "회의록 및 번역 모델";
"纪要整理好了" = "회의록 정리 완료";
+"虚拟麦克风没装上" = "가상 마이크를 설치하지 못했습니다";
"要粘贴 sk- 开头的那串" = "sk-로 시작하는 키를 붙여넣어 주세요";
"设置知了" = "Cicada 설정";
"识别、翻译和纪要都靠它。到 Ling 开放平台点“创建令牌”,复制 sk- 开头的那串,粘贴到下面。" = "음성 인식, 번역, 회의록 작성에 모두 사용됩니다. Ling 오픈 플랫폼에서 '토큰 생성'을 클릭한 후, sk-로 시작하는 키를 복사해 아래에 붙여넣으세요.";
@@ -89,11 +114,18 @@
"还没填 key" = "아직 키를 입력하지 않음";
"还没接上 Ling" = "Ling에 연결되지 않음";
"还没有会议记录" = "아직 회의 기록이 없습니다";
+"还没装虚拟麦克风,去设置里装一下" = "가상 마이크가 아직 설치되지 않았습니다. 설정에서 설치해 주세요";
"这个 key 不能用,检查是否复制完整,或重新创建一个" = "이 키는 사용할 수 없습니다. 전체를 복사했는지 확인하거나 새로 만들어 보세요.";
"这个快捷键被别的程序占用了" = "이 단축키는 다른 프로그램에서 이미 사용 중입니다";
+"这台电脑没有这种语言的声音,没有发出去" = "이 PC에 해당 언어의 음성이 없어 전송하지 않았습니다";
"这段时间的话没能识别。检查网络后点重试。" = "이 구간의 음성을 인식하지 못했습니다. 네트워크를 확인한 후 다시 시도하세요.";
"连不上 Ling" = "Ling에 연결할 수 없음";
"连不上 Ling,检查网络" = "Ling에 연결할 수 없습니다. 네트워크를 확인하세요.";
+"连不上 Ling,没有发出去" = "Ling에 연결할 수 없어 전송하지 않았습니다";
"重命名" = "이름 바꾸기";
"重新打开知了后生效" = "Cicada를 다시 시작하면 적용됩니다";
"隐私与启动" = "개인정보 및 시작";
+"需要 Ling key 才能说" = "말하려면 Ling 키가 필요합니다";
+"需要你在 Windows 的提示里点“是”才能安装。" = "설치하려면 Windows 알림 창에서 '예'를 눌러야 합니다.";
+"需要装免费的 VB-Cable;装的时候 Windows 会请你确认" = "무료 VB-Cable 설치가 필요합니다. 설치할 때 Windows에서 확인을 요청합니다";
+"麦克风打不开" = "마이크를 열 수 없습니다";
diff --git a/windows/src/Cicada/TrayFlyout.cs b/windows/src/Cicada/TrayFlyout.cs
index 0a01ad4..9c0147b 100644
--- a/windows/src/Cicada/TrayFlyout.cs
+++ b/windows/src/Cicada/TrayFlyout.cs
@@ -86,7 +86,7 @@ sealed class TrayFlyout : Window
else
{
main.Children.Add(Ui.Button(L("开始听"), () => { Hide(); _ = app.ToggleListening(); }, Ui.Kind.Accent, Icons.Wave, 52));
- var hint = Ui.Text($"{L("听电脑播放的声音,不用麦克风")} · {Hotkey.Label}", 12, Palette.Secondary);
+ var hint = Ui.Text(app.Settings.Speak ? $"{Hotkey.Label} · {LF("按住%@说话", PushToTalk.Label)}" : $"{L("听电脑播放的声音,不用麦克风")} · {Hotkey.Label}", 12, Palette.Secondary);
hint.TextAlignment = TextAlignment.Center; hint.Margin = new Thickness(0, 8, 0, 0);
main.Children.Add(hint);
}
diff --git a/windows/src/Cicada/Ui.cs b/windows/src/Cicada/Ui.cs
index f2d154c..b1944a1 100644
--- a/windows/src/Cicada/Ui.cs
+++ b/windows/src/Cicada/Ui.cs
@@ -70,6 +70,7 @@ static class Icons
public const string Chevron = "M6,8 L10,12 L14,8";
public const string Check = "M4.5,10.5 L8,14 L15.5,6";
public const string Info = "M17,10 A7,7 0 1 1 3,10 A7,7 0 1 1 17,10 Z M10,9 V14 M10,6.5 V7";
+ public const string Mic = "M10,2.5 A2.5,2.5 0 0 1 12.5,5 V10 A2.5,2.5 0 0 1 7.5,10 V5 A2.5,2.5 0 0 1 10,2.5 Z M5,9.5 A5,5 0 0 0 15,9.5 M10,14.5 V17.5";
public const string OpenExternal = "M8,4 H4.5 V15.5 H16 V12 M11,3.5 H16.5 V9 M16.5,3.5 L9,11";
}
diff --git a/windows/src/Cicada/Wasapi.cs b/windows/src/Cicada/Wasapi.cs
new file mode 100644
index 0000000..bc5f3e5
--- /dev/null
+++ b/windows/src/Cicada/Wasapi.cs
@@ -0,0 +1,314 @@
+using System.Runtime.InteropServices;
+
+namespace Cicada.App;
+
+/// Audio devices by name, and plain WASAPI capture and playback on them: the microphone (what I
+/// say), the virtual cable's "CABLE Input" (what the meeting hears), the speakers (previews).
+/// SystemAudioTap is the other half, the process loopback.
+static class Endpoints
+{
+ public enum Flow { Render = 0, Capture = 1 }
+ public sealed record Device(string Id, string Name, string Description);
+
+ /// Active devices: Name is "扬声器 (Realtek…)", Description the short "CABLE Input".
+ public static List<Device> All(Flow flow)
+ {
+ var list = new List<Device>();
+ try
+ {
+ var e = (IMMDeviceEnumerator)new MMDeviceEnumerator();
+ Marshal.ThrowExceptionForHR(e.EnumAudioEndpoints((int)flow, 1 /* ACTIVE */, out var all));
+ all.GetCount(out var n);
+ for (uint i = 0; i < n; i++)
+ {
+ all.Item(i, out var d);
+ d.GetId(out var id);
+ list.Add(new Device(id, Prop(d, 14) ?? id, Prop(d, 2) ?? ""));
+ }
+ }
+ catch (Exception ex) { Log.Debug($"endpoints: list failed {ex.GetType().Name}"); }
+ return list;
+ }
+
+ public static Device? Default(Flow flow)
+ {
+ try
+ {
+ var e = (IMMDeviceEnumerator)new MMDeviceEnumerator();
+ if (e.GetDefaultAudioEndpoint((int)flow, 1 /* eMultimedia */, out var d) != 0) return null;
+ d.GetId(out var id);
+ return new Device(id, Prop(d, 14) ?? id, Prop(d, 2) ?? "");
+ }
+ catch { return null; }
+ }
+
+ /// The virtual cable's playback side, which meeting apps hear as the "CABLE Output" mic.
+ public static Device? Cable() => All(Flow.Render).FirstOrDefault(d => d.Description == VirtualCable.InputName || d.Name.StartsWith(VirtualCable.InputName));
+ public static Device? CableOutput() => All(Flow.Capture).FirstOrDefault(d => d.Description == VirtualCable.OutputName || d.Name.StartsWith(VirtualCable.OutputName));
+
+ /// A microphone, never the cable's own output (that would be the room hearing itself).
+ public static Device? Microphone()
+ {
+ var d = Default(Flow.Capture);
+ if (d is not null && d.Description != VirtualCable.OutputName && !d.Name.StartsWith(VirtualCable.OutputName)) return d;
+ return All(Flow.Capture).FirstOrDefault(x => x.Description != VirtualCable.OutputName && !x.Name.StartsWith(VirtualCable.OutputName));
+ }
+
+ static string? Prop(IMMDevice d, int pid)
+ {
+ if (d.OpenPropertyStore(0, out var store) != 0) return null;
+ var key = new PropertyKey { fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pid = pid };
+ if (store.GetValue(ref key, out var v) != 0) return null;
+ var s = v.vt == 31 ? Marshal.PtrToStringUni(v.pointer) : null;
+ PropVariantClear(ref v);
+ return s;
+ }
+
+ internal static IAudioClient Activate(string id)
+ {
+ var e = (IMMDeviceEnumerator)new MMDeviceEnumerator();
+ Marshal.ThrowExceptionForHR(e.GetDevice(id, out var d));
+ var iid = typeof(IAudioClient).GUID;
+ Marshal.ThrowExceptionForHR(d.Activate(ref iid, 23 /* CLSCTX_ALL */, IntPtr.Zero, out var o));
+ return (IAudioClient)o;
+ }
+
+ internal static IntPtr Pcm16(int rate)
+ {
+ var p = Marshal.AllocHGlobal(18);
+ var b = new byte[18];
+ BitConverter.GetBytes((ushort)1).CopyTo(b, 0); BitConverter.GetBytes((ushort)1).CopyTo(b, 2);
+ BitConverter.GetBytes(rate).CopyTo(b, 4); BitConverter.GetBytes(rate * 2).CopyTo(b, 8);
+ BitConverter.GetBytes((ushort)2).CopyTo(b, 12); BitConverter.GetBytes((ushort)16).CopyTo(b, 14);
+ Marshal.Copy(b, 0, p, 18);
+ return p;
+ }
+
+ internal const uint AutoConvert = 0x80000000 | 0x08000000; // AUTOCONVERTPCM | SRC_DEFAULT_QUALITY
+
+ // MARK: COM
+
+ [ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumerator { }
+
+ [ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ interface IMMDeviceEnumerator
+ {
+ [PreserveSig] int EnumAudioEndpoints(int dataFlow, int stateMask, out IMMDeviceCollection devices);
+ [PreserveSig] int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice device);
+ [PreserveSig] int GetDevice([MarshalAs(UnmanagedType.LPWStr)] string id, out IMMDevice device);
+ }
+
+ [ComImport, Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ interface IMMDeviceCollection
+ {
+ [PreserveSig] int GetCount(out uint count);
+ [PreserveSig] int Item(uint index, out IMMDevice device);
+ }
+
+ [ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ interface IMMDevice
+ {
+ [PreserveSig] int Activate(ref Guid iid, int clsCtx, IntPtr activationParams, [MarshalAs(UnmanagedType.IUnknown)] out object iface);
+ [PreserveSig] int OpenPropertyStore(int access, out IPropertyStore store);
+ [PreserveSig] int GetId([MarshalAs(UnmanagedType.LPWStr)] out string id);
+ [PreserveSig] int GetState(out int state);
+ }
+
+ [ComImport, Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ interface IPropertyStore
+ {
+ [PreserveSig] int GetCount(out int count);
+ [PreserveSig] int GetAt(int index, out PropertyKey key);
+ [PreserveSig] int GetValue(ref PropertyKey key, out PropVariant value);
+ }
+
+ [StructLayout(LayoutKind.Sequential)] struct PropertyKey { public Guid fmtid; public int pid; }
+ [StructLayout(LayoutKind.Explicit, Size = 24)] struct PropVariant { [FieldOffset(0)] public ushort vt; [FieldOffset(8)] public IntPtr pointer; }
+ [DllImport("ole32.dll")] static extern int PropVariantClear(ref PropVariant value);
+}
+
+[ComImport, Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+interface IAudioClient
+{
+ [PreserveSig] int Initialize(int shareMode, uint streamFlags, long bufferDuration, long periodicity, IntPtr format, IntPtr sessionGuid);
+ [PreserveSig] int GetBufferSize(out uint frames);
+ [PreserveSig] int GetStreamLatency(out long latency);
+ [PreserveSig] int GetCurrentPadding(out uint padding);
+ [PreserveSig] int IsFormatSupported(int shareMode, IntPtr format, out IntPtr closest);
+ [PreserveSig] int GetMixFormat(out IntPtr format);
+ [PreserveSig] int GetDevicePeriod(out long defaultPeriod, out long minimumPeriod);
+ [PreserveSig] int Start();
+ [PreserveSig] int Stop();
+ [PreserveSig] int Reset();
+ [PreserveSig] int SetEventHandle(IntPtr handle);
+ [PreserveSig] int GetService(ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object service);
+}
+
+[ComImport, Guid("C8ADBD64-E71E-48a0-A4DE-185C395CD317"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+interface IAudioCaptureClient
+{
+ [PreserveSig] int GetBuffer(out IntPtr data, out uint frames, out uint flags, out ulong devicePosition, out ulong qpcPosition);
+ [PreserveSig] int ReleaseBuffer(uint frames);
+ [PreserveSig] int GetNextPacketSize(out uint frames);
+}
+
+[ComImport, Guid("F294ACFC-3146-4483-A7BF-ADDCA7C260E2"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+interface IAudioRenderClient
+{
+ [PreserveSig] int GetBuffer(uint frames, out IntPtr data);
+ [PreserveSig] int ReleaseBuffer(uint frames, uint flags);
+}
+
+/// Records one device at 16 kHz mono (Windows converts) until Stop: the mic while the key is held,
+/// or CABLE Output in tests (what the meeting would hear).
+sealed class DeviceRecorder
+{
+ readonly string id;
+ readonly List<short> samples = [];
+ Thread? thread;
+ volatile bool running;
+ public string? Error { get; private set; }
+
+ public DeviceRecorder(string id) { this.id = id; }
+
+ public void Start()
+ {
+ running = true;
+ var ready = new ManualResetEventSlim();
+ thread = new Thread(() => Run(ready)) { IsBackground = true, Name = "DeviceRecorder" };
+ thread.SetApartmentState(ApartmentState.MTA);
+ thread.Start();
+ ready.Wait(2000);
+ }
+
+ public short[] Stop()
+ {
+ running = false;
+ thread?.Join(1500);
+ lock (samples) return [.. samples];
+ }
+
+ void Run(ManualResetEventSlim ready)
+ {
+ IAudioClient? client = null;
+ try
+ {
+ client = Endpoints.Activate(id);
+ var fmt = Endpoints.Pcm16(16000);
+ int hr = client.Initialize(0, Endpoints.AutoConvert, 2_000_000, 0, fmt, IntPtr.Zero);
+ Marshal.FreeHGlobal(fmt);
+ Marshal.ThrowExceptionForHR(hr);
+ var iid = typeof(IAudioCaptureClient).GUID;
+ Marshal.ThrowExceptionForHR(client.GetService(ref iid, out var s));
+ var cap = (IAudioCaptureClient)s;
+ Marshal.ThrowExceptionForHR(client.Start());
+ ready.Set();
+ while (running)
+ {
+ Thread.Sleep(10);
+ while (cap.GetNextPacketSize(out var n) == 0 && n > 0)
+ {
+ if (cap.GetBuffer(out var data, out var frames, out var flags, out _, out _) != 0) break;
+ var buf = new short[frames];
+ if ((flags & 0x2) == 0) Marshal.Copy(data, buf, 0, (int)frames);
+ cap.ReleaseBuffer(frames);
+ lock (samples) samples.AddRange(buf);
+ }
+ }
+ client.Stop();
+ }
+ catch (Exception e)
+ {
+ // 0x80070005: Windows' microphone privacy switch is off for desktop apps.
+ Error = e.HResult == unchecked((int)0x80070005) ? "denied" : e.GetType().Name;
+ Log.Debug($"recorder: failed 0x{e.HResult:X8}");
+ ready.Set();
+ }
+ finally { if (client is not null) Marshal.ReleaseComObject(client); }
+ }
+}
+
+/// Plays a sentence on one device: the virtual cable for the room, the speakers for a preview.
+/// Chunks are queued as they stream in and played as soon as the first arrives; End waits for the
+/// last sample to be heard.
+sealed class DeviceSpeaker : ISpeechSink
+{
+ readonly Func<Endpoints.Device?> device;
+ readonly Queue<byte[]> queue = new();
+ Thread? thread;
+ volatile bool ending;
+ TaskCompletionSource? done;
+ int rate;
+ public string? DeviceName { get; private set; }
+
+ public DeviceSpeaker(Func<Endpoints.Device?> device) { this.device = device; }
+
+ public void Begin(int rate)
+ {
+ this.rate = rate;
+ ending = false;
+ lock (queue) queue.Clear();
+ done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var d = device();
+ DeviceName = d?.Name;
+ if (d is null) { Log.Debug("speaker: no device"); done.TrySetResult(); return; }
+ thread = new Thread(() => Run(d.Id)) { IsBackground = true, Name = "DeviceSpeaker" };
+ thread.SetApartmentState(ApartmentState.MTA);
+ thread.Start();
+ }
+
+ public void Write(byte[] pcm) { lock (queue) queue.Enqueue(pcm); }
+
+ public Task End() { ending = true; return done?.Task ?? Task.CompletedTask; }
+
+ void Run(string id)
+ {
+ IAudioClient? client = null;
+ try
+ {
+ client = Endpoints.Activate(id);
+ var fmt = Endpoints.Pcm16(rate);
+ int hr = client.Initialize(0, Endpoints.AutoConvert, 2_000_000, 0, fmt, IntPtr.Zero);
+ Marshal.FreeHGlobal(fmt);
+ Marshal.ThrowExceptionForHR(hr);
+ client.GetBufferSize(out var size);
+ var iid = typeof(IAudioRenderClient).GUID;
+ Marshal.ThrowExceptionForHR(client.GetService(ref iid, out var s));
+ var render = (IAudioRenderClient)s;
+ byte[] pending = [];
+ int offset = 0;
+ bool started = false;
+ while (true)
+ {
+ client.GetCurrentPadding(out var padding);
+ var room = (int)(size - padding);
+ if (offset >= pending.Length)
+ {
+ lock (queue) { if (queue.Count > 0) { pending = queue.Dequeue(); offset = 0; } }
+ }
+ if (offset < pending.Length && room > 0)
+ {
+ int frames = Math.Min(room, (pending.Length - offset) / 2);
+ if (frames > 0 && render.GetBuffer((uint)frames, out var data) == 0)
+ {
+ Marshal.Copy(pending, offset, data, frames * 2);
+ render.ReleaseBuffer((uint)frames, 0);
+ offset += frames * 2;
+ if (!started) { Marshal.ThrowExceptionForHR(client.Start()); started = true; }
+ }
+ continue;
+ }
+ bool empty; lock (queue) empty = queue.Count == 0;
+ if (ending && empty && offset >= pending.Length && padding == 0) break;
+ Thread.Sleep(10);
+ }
+ client.Stop();
+ }
+ catch (Exception e) { Log.Debug($"speaker: failed 0x{e.HResult:X8}"); }
+ finally
+ {
+ if (client is not null) Marshal.ReleaseComObject(client);
+ done?.TrySetResult();
+ }
+ }
+}
diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.cs
index 04e2dbf..7aa546b 100644
--- a/windows/tests/Cicada.Tests/Program.cs
+++ b/windows/tests/Cicada.Tests/Program.cs
@@ -140,7 +140,7 @@ static class Tests
public static void DropsLoneFillers()
{
- Check(Translator.IsFiller("嗯。") && Translator.IsFiller("Mm.") && Translator.IsFiller("uh, um"), "fillers");
+ Check(Translator.IsFiller("嗯。") && Translator.IsFiller("Mm.") && Translator.IsFiller("uh, um") && Translator.IsFiller("呃呃呃呃呃"), "fillers");
Check(!Translator.IsFiller("嗯,好的。") && !Translator.IsFiller("OK.") && !Translator.IsFiller("Oh no, it crashed."), "real lines stay");
}
@@ -409,6 +409,90 @@ static class Tests
finally { LingClient.Spacing = old; }
}
+ // MARK: Speaking
+
+ sealed class Sink : ISpeechSink
+ {
+ public int Rate; public readonly List<byte[]> Chunks = [];
+ public void Begin(int rate) => Rate = rate;
+ public void Write(byte[] pcm) => Chunks.Add(pcm);
+ public Task End() => Task.CompletedTask;
+ }
+
+ sealed class NoVoice : ISystemVoice
+ {
+ public int Calls;
+ public Task<(byte[] pcm, int rate)?> Speak(string text, string language) { Calls++; return Task.FromResult<(byte[], int)?>((new byte[480], 16000)); }
+ public bool Has(string language) => true;
+ }
+
+ public static void ParsesMingVoiceStream()
+ {
+ var pcm = LingClient.SpeechChunk("data:{\"type\":\"speech.audio.delta\",\"audio\":\"AQIDBA==\"}", out var done);
+ Check(!done && pcm is { Length: 4 } && pcm[3] == 4, "a delta carries its PCM");
+ LingClient.SpeechChunk("data:{\"type\":\"speech.audio.done\"}", out done);
+ Check(done, "done ends the stream");
+ Check(LingClient.SpeechChunk(": keep-alive", out _) is null && LingClient.SpeechChunk("data:{oops", out _) is null, "noise is skipped");
+ }
+
+ public static void PicksTheRoomsLanguage()
+ {
+ Equal("en", SpeakEngine.TargetFor("room", "en", "zh-CN"), "the language the other side speaks");
+ Equal("en", SpeakEngine.TargetFor("room", null, "zh-CN"), "English before anyone spoke");
+ Equal("en", SpeakEngine.TargetFor("room", "zh-CN", "zh-CN"), "never my own language");
+ Equal("zh-CN", SpeakEngine.TargetFor("room", "en", "en"), "an English speaker in an English room gets Chinese");
+ Equal("ja", SpeakEngine.TargetFor("ja", "en", "zh-CN"), "a chosen language wins");
+ }
+
+ public static void ChecksTheVirtualCablePackage()
+ {
+ Check(!VirtualCable.Verify("not the package"u8.ToArray()), "anything else is refused");
+ Equal(64, VirtualCable.PackageSha256.Length, "a full SHA-256 is pinned");
+ }
+
+ static SpeakEngine Speaker(LingClient ling, NoVoice voice, AppSettings? settings = null) =>
+ new(ling, new Translator(ling), new SessionStore(), settings ?? new AppSettings(), () => "en", () => null, voice);
+
+ public static async Task SpeaksTheTranslationNeverTheOriginal()
+ {
+ var old = LingClient.Spacing;
+ LingClient.Spacing = 0.01;
+ try
+ {
+ // Ming hears and translates; Ming's voice streams two chunks.
+ var spoken = new List<string>();
+ var fake = new Fake(body =>
+ {
+ if (body.Contains(LingClient.AudioModel)) return Reply("LANG: zh-CN\nORIGINAL: 我们周三能测完吗?\nTRANSLATION: Can we finish testing by Wednesday?");
+ if (body.Contains(LingClient.VoiceModel))
+ {
+ lock (spoken) spoken.Add(JsonNode.Parse(body)!["input"]!.GetValue<string>());
+ return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("data:{\"type\":\"speech.audio.delta\",\"audio\":\"AAABAA==\"}\n\ndata:{\"type\":\"speech.audio.delta\",\"audio\":\"AgADAA==\"}\n\ndata:{\"type\":\"speech.audio.done\"}\n\n") };
+ }
+ return Reply("x");
+ });
+ var voice = new NoVoice();
+ var sink = new Sink();
+ var engine = Speaker(Client(fake), voice, new AppSettings { SpeakFrom = "zh-CN" });
+ var heard = await engine.Speak(Wav.Bytes(Tone(1)), sink);
+ Equal("Can we finish testing by Wednesday?", heard, "the room hears the translation");
+ Equal("Can we finish testing by Wednesday?", spoken.Single(), "and only it is voiced");
+ Check(sink.Rate == 24000 && sink.Chunks.Count == 2, "Ming's 24 kHz stream reaches the virtual mic");
+ Equal("ming", engine.LastVoice, "voiced by Ming");
+
+ // No translation (Ming echoes the original, Ling and Google fail): nothing reaches the room.
+ var echo = new Fake(body => body.Contains(LingClient.AudioModel)
+ ? Reply("LANG: zh-CN\nORIGINAL: 我们周三能测完吗?\nTRANSLATION: 我们周三能测完吗?")
+ : new HttpResponseMessage(HttpStatusCode.InternalServerError));
+ var quiet = new Sink();
+ var voice2 = new NoVoice();
+ var e2 = Speaker(Client(echo), voice2, new AppSettings { SpeakFrom = "zh-CN" });
+ Check(await e2.Speak(Wav.Bytes(Tone(1)), quiet) is null, "no translation, nothing said");
+ Check(quiet.Chunks.Count == 0 && voice2.Calls == 0 && e2.State == SpeakEngine.Phase.Failed, "and no voice at all");
+ }
+ finally { LingClient.Spacing = old; }
+ }
+
public static async Task ListenEngineEndToEndWithAFakeMing()
{
// Two stretches of "speech", told apart by length (1 s, then 1.6 s); the fake Ming
diff --git a/windows/vm/guest.ps1 b/windows/vm/guest.ps1
index 92987cb..a62e8f5 100644
--- a/windows/vm/guest.ps1
+++ b/windows/vm/guest.ps1
@@ -20,6 +20,7 @@ public static class W {
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr h, StringBuilder s, int n);
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
[DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
+ [DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
[DllImport("user32.dll")] public static extern void mouse_event(uint f, int x, int y, uint d, UIntPtr e);
[DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
public delegate bool EnumProc(IntPtr h, IntPtr l);