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): Interpreting can speak in your own voice: record 15 seconds and the meeting hears your translation in it (#32)

wquguru29cf959d69f6
diff --git a/windows/src/Cicada.Cli/Program.cs b/windows/src/Cicada.Cli/Program.cs
index f0472bb..b49aa6a 100644
--- a/windows/src/Cicada.Cli/Program.cs
+++ b/windows/src/Cicada.Cli/Program.cs
@@ -6,7 +6,9 @@
// for the final notes and prints them. --room <mic.wav> hears that file as the room mic too
// (电脑和会议室: two engines, the echo gate and EchoMatch); --room-only hears it alone (会议室).
// cicada-cli check the AI service's key check: state, hears, catalog sizes
-// cicada-cli speak <text> <out.wav> the service's voice for <text>, as a 24 kHz WAV
+// cicada-cli speak <text> <out.wav> the service's voice for <text>, as a 24 kHz WAV; --voice <id>,
+// --lang <code> (Ming's language_id), --clone <reference.wav> [--clone-text <what it says>]
+// [--from <my language>] for the user's own voice (Ling only)
// cicada-cli segments <file.wav> where the segmenter cuts (compare with ming_asr.py)
// cicada-cli roundtrip <session.json>… reads and writes records, says if anything changed
//
@@ -73,8 +75,29 @@ switch (args_[0])
{
var ling = Client();
var pcm = new List<byte>();
+ // --clone <reference.wav>: the user's own voice, as 我自己的声音 does. The clip is checked
+ // as the app checks a recording (length, heard by the hear model, pace) unless --clone-text
+ // gives what it says.
+ (string Audio, string Text)? reference = null;
+ if (Opt("--clone", "") is { Length: > 0 } refFile)
+ {
+ var refWav = Wav.Bytes(Wav.Read(refFile));
+ var text = Opt("--clone-text", "");
+ if (text.Length == 0)
+ {
+ var me = Opt("--from", "zh-CN");
+ var (outcome, heard) = await VoiceCloneCheck.Check(refWav,
+ async w => (await new Translator(ling).Hear(w, SpeakEngine.TargetFor("room", "en", me), me, Priority.Speak))?.Original);
+ Console.WriteLine($"reference: {(refWav.Length - 44) / 32000.0:F1} s, {outcome}, heard «{heard}»");
+ if (outcome != VoiceCloneCheck.Outcome.Ready) return 1;
+ text = heard;
+ }
+ reference = ("data:audio/wav;base64," + Convert.ToBase64String(refWav), text);
+ }
+ var lang = Opt("--lang", "");
var started = DateTime.UtcNow;
- await foreach (var chunk in ling.Speech(args_[1], Opt("--voice", "") is { Length: > 0 } v ? v : null)) pcm.AddRange(chunk);
+ await foreach (var chunk in ling.Speech(args_[1], Opt("--voice", "") is { Length: > 0 } v ? v : null,
+ lang.Length > 0 ? VoiceCatalog.MingLanguage(lang) : null, reference)) pcm.AddRange(chunk);
var samples = new short[pcm.Count / 2];
Buffer.BlockCopy(pcm.ToArray(), 0, samples, 0, samples.Length * 2);
File.WriteAllBytes(args_[2], Wav.Bytes(samples, 24000));
diff --git a/windows/src/Cicada.Core/Ling.cs b/windows/src/Cicada.Core/Ling.cs
index dd85c1d..6659ce7 100644
--- a/windows/src/Cicada.Core/Ling.cs
+++ b/windows/src/Cicada.Core/Ling.cs
@@ -231,6 +231,8 @@ public sealed class LingClient
public bool Usable => HasKey && KeyState != KeyState.Invalid;
/// Voices in the room from this service (else Windows' own voice speaks).
public bool Speaks => Usable && Config.HasVoices;
+ /// The user's own voice: only Ling clones.
+ public bool Clones => Speaks && Config.Provider.Clones;
/// Listening and 同声传译 can work: the hear model wasn't found to refuse audio.
public bool CanHear => Usable && Hears != false && Config.HearModel.Length > 0;
/// The addresses that refused `chat_template_kwargs` once (a custom service's text and hear
@@ -722,27 +724,17 @@ public sealed class LingClient
/// es (Ling.swift › speech); elsewhere the configured speech model, and a voice not in the
/// service's list becomes its first. Replies come three ways and all are read: server-sent
/// base64 chunks (Ling, ZenMux), raw PCM (OpenRouter), or one JSON `{"audio": <WAV>}`.
+ /// `reference` (Ling only): a voice cloned from the user's recording (a WAV data URI and what it
+ /// says) instead of `voice`; the whole clip goes with every sentence, so it waits longer.
public async IAsyncEnumerable<byte[]> Speech(string text, string? voice, string? languageId = null,
+ (string Audio, string Text)? reference = null,
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancel = default)
{
var k = CurrentKey() ?? throw new LingException(LingException.Kind.NoKey);
if (KeyState == KeyState.Invalid) throw new LingException(LingException.Kind.InvalidKey);
var c = Config;
if (!c.HasVoices) throw new LingException(LingException.Kind.NoKey);
- var body = new JsonObject { ["model"] = c.VoiceModel, ["input"] = text, ["response_format"] = "pcm" };
- if (c.IsLing)
- {
- body["voice"] = voice ?? "UK_Charlotte";
- body["sample_rate"] = 24000; body["stream"] = true; body["stream_format"] = "sse";
- if (languageId is not null) body["language_id"] = languageId;
- }
- else
- {
- // OpenRouter documents no `stream` (it streams the bytes anyway); ZenMux needs it.
- if (c.Provider.Id != "openrouter") body["stream"] = true;
- var ids = c.Voices.Select(v => v.Id).ToList();
- body["voice"] = voice is not null && ids.Contains(voice) ? voice : ids.FirstOrDefault() ?? c.CustomVoice ?? "Kore";
- }
+ var body = SpeechBody(c, text, voice, languageId, reference);
await Acquire(GateFor(c.VoiceBase), Priority.Speak, c.Provider.Spacing, cancel);
var started = DateTime.UtcNow;
using var req = new HttpRequestMessage(HttpMethod.Post, new Uri(new Uri(c.VoiceBase!), "audio/speech"))
@@ -751,7 +743,7 @@ public sealed class LingClient
};
if (k.Length > 0) req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", k);
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancel);
- cts.CancelAfter(TimeSpan.FromSeconds(20));
+ cts.CancelAfter(TimeSpan.FromSeconds(reference is not null && c.IsLing ? 30 : 20));
HttpResponseMessage res;
try { res = await http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token); }
catch (OperationCanceledException) when (!cancel.IsCancellationRequested) { throw new LingException(LingException.Kind.Timeout); }
@@ -823,6 +815,28 @@ public sealed class LingClient
}
}
+ /// The `/audio/speech` request (Ling.swift › speech): Ming's voice, or a clone of `reference`, on
+ /// Ling; elsewhere the configured speech model with one of its voices.
+ public static JsonObject SpeechBody(AIConfig c, string text, string? voice, string? languageId, (string Audio, string Text)? reference = null)
+ {
+ var body = new JsonObject { ["model"] = c.VoiceModel, ["input"] = text, ["response_format"] = "pcm" };
+ if (c.IsLing)
+ {
+ if (reference is { } r) body["references"] = new JsonArray(new JsonObject { ["audio"] = r.Audio, ["text"] = r.Text });
+ else body["voice"] = voice ?? "UK_Charlotte";
+ body["sample_rate"] = 24000; body["stream"] = true; body["stream_format"] = "sse";
+ if (languageId is not null) body["language_id"] = languageId;
+ }
+ else
+ {
+ // OpenRouter documents no `stream` (it streams the bytes anyway); ZenMux needs it.
+ if (c.Provider.Id != "openrouter") body["stream"] = true;
+ var ids = c.Voices.Select(v => v.Id).ToList();
+ body["voice"] = voice is not null && ids.Contains(voice) ? voice : ids.FirstOrDefault() ?? c.CustomVoice ?? "Kore";
+ }
+ return body;
+ }
+
/// The room voice spoke through this service, or failed and Windows spoke instead (现在能用的 says which).
public void VoiceSpoke(bool ok)
{
diff --git a/windows/src/Cicada.Core/Speak.cs b/windows/src/Cicada.Core/Speak.cs
index 4bcc334..af20f1e 100644
--- a/windows/src/Cicada.Core/Speak.cs
+++ b/windows/src/Cicada.Core/Speak.cs
@@ -52,8 +52,13 @@ public static class VoiceCatalog
_ => [],
};
- public static IReadOnlyList<VoiceOption> Options(string language, AIConfig config, bool windowsHasIt = true) =>
- windowsHasIt ? [.. Cloud(language, config), new(SystemId, "Windows", "本机")] : Cloud(language, config);
+ /// The user's own voice (Voices.swift › cloneOption), offered with every language once recorded.
+ public const string CloneId = "clone";
+ public static readonly VoiceOption Clone = new(CloneId, "我自己的声音", "你的音色");
+
+ /// `clone`: the user's recording exists and the service clones (Ling, with a working key).
+ public static IReadOnlyList<VoiceOption> Options(string language, AIConfig config, bool windowsHasIt = true, bool clone = false) =>
+ [.. Cloud(language, config), .. windowsHasIt ? [new VoiceOption(SystemId, "Windows", "本机")] : Array.Empty<VoiceOption>(), .. clone ? [Clone] : Array.Empty<VoiceOption>()];
/// What a language uses until the user picks: the service's first voice once it can speak (or
/// when Windows has none for the language), else Windows'.
@@ -62,9 +67,11 @@ public static class VoiceCatalog
/// The voice chosen for a language, if it is still offered: a Ming voice saved before switching
/// to ZenMux is not sent there, and "system" saved where Windows has no voice for the language
- /// (Chinese Windows often has only Chinese ones) left the voice blank and 试听 silent (#22).
- public static string Chosen(AppSettings settings, string language, AIConfig config, bool speaks, bool windowsHasIt = true) =>
- settings.SpeakVoices.TryGetValue(Key(language), out var id) && Options(language, config, windowsHasIt).Any(v => v.Id == id) ? id : DefaultId(language, config, speaks, windowsHasIt);
+ /// (Chinese Windows often has only Chinese ones) left the voice blank and 试听 silent (#22). The
+ /// user's own voice without its recording or without Ling falls back the same way, and comes
+ /// back with them (AppModel.voiceID).
+ public static string Chosen(AppSettings settings, string language, AIConfig config, bool speaks, bool windowsHasIt = true, bool clone = false) =>
+ settings.SpeakVoices.TryGetValue(Key(language), out var id) && Options(language, config, windowsHasIt, clone).Any(v => v.Id == id) ? id : DefaultId(language, config, speaks, windowsHasIt);
/// A short line to try a voice with, in the language it will speak.
public static string Sample(string language) => Key(language) switch
@@ -243,26 +250,39 @@ public sealed class SpeakEngine
store.Append(m.id, line);
}
- /// The service's voice (Ming's on Ling), else Windows'. True once some sound went out.
+ /// The user's recording for their own voice; null in tests that don't need it.
+ public VoiceReference? Reference { get; set; }
+
+ /// Whether the user's own voice can be used now: recorded, and Ling with a working key.
+ public bool CloneReady => ling.Clones && Reference?.Exists == true;
+
+ /// The voice a language uses now (the choice, or its fallback).
+ public string ChosenVoice(string language) =>
+ VoiceCatalog.Chosen(settings, language, ling.Config, ling.Speaks, systemVoice.Has(language), CloneReady);
+
+ /// The service's voice (Ming's on Ling, or the user's own cloned from their recording), else
+ /// Windows'. True once some sound went out.
public async Task<bool> Voice(string text, string language, ISpeechSink sink)
{
var config = ling.Config;
- var id = VoiceCatalog.Chosen(settings, language, config, ling.Speaks, systemVoice.Has(language));
+ var id = ChosenVoice(language);
var prefix = config.IsLing ? VoiceCatalog.MingPrefix : VoiceCatalog.CloudPrefix;
- if (id.StartsWith(prefix) && ling.Speaks)
+ var reference = id == VoiceCatalog.CloneId ? Reference?.Reference() : null;
+ if ((id.StartsWith(prefix) || reference is not null) && ling.Speaks)
{
int chunks = 0;
try
{
- await foreach (var pcm in ling.Speech(text, id[prefix.Length..], config.IsLing ? VoiceCatalog.MingLanguage(language) : null))
+ var voice = reference is null ? id[prefix.Length..] : null;
+ await foreach (var pcm in ling.Speech(text, voice, config.IsLing ? VoiceCatalog.MingLanguage(language) : null, reference))
{
if (chunks++ == 0) sink.Begin(24000);
sink.Write(pcm);
}
}
- catch (LingException e) { Log.Debug($"speak: {config.Provider.Id} voice failed {e.Message}"); }
+ catch (LingException e) { Log.Debug($"speak: {config.Provider.Id} {(reference is null ? "voice" : "cloned voice")} failed {e.Message}"); }
ling.VoiceSpoke(chunks > 0);
- if (chunks > 0) { await sink.End(); LastVoice = config.IsLing ? "ming" : "cloud"; return true; }
+ if (chunks > 0) { await sink.End(); LastVoice = reference is not null ? "clone" : config.IsLing ? "ming" : "cloud"; return true; }
}
var own = await systemVoice.Speak(text, language);
if (own is not { } v || v.pcm.Length == 0) { LastVoice = null; return false; }
diff --git a/windows/src/Cicada.Core/VoiceClone.cs b/windows/src/Cicada.Core/VoiceClone.cs
new file mode 100644
index 0000000..c60a984
--- /dev/null
+++ b/windows/src/Cicada.Core/VoiceClone.cs
@@ -0,0 +1,205 @@
+using System.Text;
+
+namespace Cicada;
+
+/// The recording Ming clones the user's voice from (Voices.swift › VoiceReference): `voice\reference.wav`
+/// (16 kHz mono, 10–15 s) and `voice\reference.txt` (what it says, as Ming heard it) under the app's
+/// folder, sealed with DPAPI like the keys. Never in a record, an export or the log; it leaves the
+/// PC only inside a speech request to Ling.
+public sealed class VoiceReference(IKeyProtector protector, string? folder = null)
+{
+ /// Shorter than the Mac's 8–30 s (#32): every cloned sentence sends the whole clip again, so a
+ /// long one makes each sentence later. At 15 s the recording stops by itself.
+ public const double MinSeconds = 10, MaxSeconds = 15;
+
+ public string Folder => folder ?? Path.Combine(Paths.Root, "voice");
+ public string AudioFile => Path.Combine(Folder, "reference.wav");
+ public string TextFile => Path.Combine(Folder, "reference.txt");
+
+ const string Sealed = "dpapi:";
+ readonly object gate = new();
+ (DateTime at, byte[]? wav, string? text)? cache;
+
+ /// Fired when the recording is saved or removed.
+ public event Action? Changed;
+
+ public bool Exists => Load() is { wav: not null, text: { Length: > 0 } };
+ public string? Text => Load().text;
+ public byte[]? Wav => Load().wav;
+
+ /// Seconds in the saved clip (16 kHz mono 16-bit after a 44-byte header).
+ public double Duration => Wav is { } w ? Math.Max(0, w.Length - 44) / 32000.0 : 0;
+
+ /// What Ming needs: the clip as a data URI and its transcript.
+ public (string Audio, string Text)? Reference() =>
+ Load() is { wav: { } w, text: { Length: > 0 } t } ? ("data:audio/wav;base64," + Convert.ToBase64String(w), t) : null;
+
+ (byte[]? wav, string? text) Load()
+ {
+ lock (gate)
+ {
+ var at = File.Exists(AudioFile) ? File.GetLastWriteTimeUtc(AudioFile) : DateTime.MinValue;
+ if (cache is { } c && c.at == at) return (c.wav, c.text);
+ byte[]? wav = null; string? text = null;
+ try
+ {
+ if (File.Exists(AudioFile) && File.Exists(TextFile))
+ {
+ wav = Open(File.ReadAllText(AudioFile));
+ text = Open(File.ReadAllText(TextFile)) is { } t ? Encoding.UTF8.GetString(t).Trim() : null;
+ }
+ }
+ catch (Exception e) { Log.Debug($"voice clone: read failed {e.GetType().Name}"); wav = null; text = null; }
+ cache = (at, wav, text);
+ return (wav, text);
+ }
+ }
+
+ byte[]? Open(string body) =>
+ body.StartsWith(Sealed) ? (protector.Tag == "plain" ? Convert.FromBase64String(body[Sealed.Length..]) : protector.Unprotect(Convert.FromBase64String(body[Sealed.Length..]))) : null;
+
+ string Seal(byte[] data) => Sealed + Convert.ToBase64String(protector.Tag == "plain" ? data : protector.Protect(data));
+
+ public void Save(byte[] wav, string text)
+ {
+ lock (gate)
+ {
+ Directory.CreateDirectory(Folder);
+ if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(Folder, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+ File.WriteAllText(TextFile, Seal(Encoding.UTF8.GetBytes(text.Trim())));
+ File.WriteAllText(AudioFile, Seal(wav));
+ if (!OperatingSystem.IsWindows())
+ foreach (var f in new[] { AudioFile, TextFile }) File.SetUnixFileMode(f, UnixFileMode.UserRead | UnixFileMode.UserWrite);
+ cache = null;
+ slow = null;
+ }
+ Changed?.Invoke();
+ }
+
+ public void Remove()
+ {
+ lock (gate)
+ {
+ try { if (Directory.Exists(Folder)) Directory.Delete(Folder, true); } catch (Exception e) { Log.Debug($"voice clone: remove failed {e.GetType().Name}"); }
+ cache = null;
+ slow = null;
+ }
+ Changed?.Invoke();
+ }
+
+ (DateTime at, bool slow)? slow;
+
+ /// The saved recording is read too slowly (worked out once per recording).
+ public bool SavedIsSlow
+ {
+ get
+ {
+ var at = File.Exists(AudioFile) ? File.GetLastWriteTimeUtc(AudioFile) : DateTime.MinValue;
+ if (slow is { } s && s.at == at) return s.slow;
+ var result = Load() is { wav: { } w, text: { } t } && VoicePace.Pace(t, VoicePace.Samples(w), 16000) is { } p && VoicePace.IsSlow(t, p);
+ slow = (at, result);
+ return result;
+ }
+ }
+}
+
+/// How fast a recording is read (Voices.swift › VoiceReference's pace): Ming copies the clip's pace
+/// into every sentence, so a recital at 1.7 characters a second made each sentence about 4× as long.
+public static class VoicePace
+{
+ /// Characters (Chinese, Japanese, Korean) or words a second below which the clone is too slow
+ /// for a meeting; an ordinary pace gives 3.5–5 and 2.3–3.
+ public const double SlowCharacters = 2.5, SlowWords = 1.6;
+
+ public static double? Pace(string text, float[] samples, double sampleRate)
+ {
+ var units = Tokens(text).Count;
+ if (units == 0 || SpeechSpan(samples, sampleRate) is not { } span || span <= 0.5) return null;
+ return units / span;
+ }
+
+ public static bool IsSlow(string text, double pace)
+ {
+ var tokens = Tokens(text);
+ var characters = tokens.Count(t => t.Any(IsCjk));
+ return pace < (characters * 2 >= tokens.Count ? SlowCharacters : SlowWords);
+ }
+
+ /// Seconds from the first to the last 20 ms window within 35 dB of the loudest one.
+ public static double? SpeechSpan(float[] samples, double sampleRate)
+ {
+ var size = Math.Max(1, (int)(sampleRate * 0.02));
+ var levels = new List<float>();
+ for (var i = 0; i < samples.Length; i += size)
+ {
+ var end = Math.Min(samples.Length, i + size);
+ float sum = 0;
+ for (var k = i; k < end; k++) sum += samples[k] * samples[k];
+ levels.Add(MathF.Sqrt(sum / (end - i)));
+ }
+ if (levels.Count == 0) return null;
+ var loudest = levels.Max();
+ if (loudest <= 0.003f) return null;
+ var floor = loudest * 0.0178f;
+ var first = levels.FindIndex(l => l >= floor);
+ var last = levels.FindLastIndex(l => l >= floor);
+ return (last - first + 1) * (double)size / sampleRate;
+ }
+
+ /// Words, and each CJK character on its own (SpeakTest.swift › SpeakScore.tokens).
+ public static List<string> Tokens(string text)
+ {
+ var out_ = new List<string>();
+ var word = new StringBuilder();
+ void Flush() { if (word.Length > 0) { out_.Add(word.ToString().ToLowerInvariant()); word.Clear(); } }
+ foreach (var ch in text)
+ {
+ if (IsCjk(ch)) { Flush(); out_.Add(ch.ToString()); }
+ else if (char.IsLetterOrDigit(ch) || ch == '\'' || ch == '’') word.Append(ch == '’' ? '\'' : ch);
+ else Flush();
+ }
+ Flush();
+ return out_;
+ }
+
+ public static bool IsCjk(char c) => c is (>= '぀' and <= 'ヿ') or (>= '㐀' and <= '䶿') or (>= '一' and <= '鿿') or (>= '가' and <= '힯') or (>= '豈' and <= '﫿');
+
+ /// A 16-bit mono WAV (or bare PCM) as samples in −1…1.
+ public static float[] Samples(byte[] wav)
+ {
+ var start = wav.Length >= 44 && wav[0] == 'R' && wav[1] == 'I' ? 44 : 0;
+ var n = (wav.Length - start) / 2;
+ var out_ = new float[n];
+ for (var i = 0; i < n; i++) out_[i] = BitConverter.ToInt16(wav, start + i * 2) / 32768f;
+ return out_;
+ }
+}
+
+/// What a recording for the clone comes to (the Mac's VoiceRecorder.finish): ready with its
+/// transcript, or why not. Kept apart from the microphone so it can be tested.
+public static class VoiceCloneCheck
+{
+ public enum Outcome { Ready, TooShort, NotHeard, Slow }
+
+ public static async Task<(Outcome outcome, string text)> Check(byte[] wav, Func<byte[], Task<string?>> transcribe)
+ {
+ var seconds = Math.Max(0, wav.Length - 44) / 32000.0;
+ if (seconds < VoiceReference.MinSeconds) return (Outcome.TooShort, "");
+ string? text = null;
+ try { text = await transcribe(wav); } catch (LingException e) { Log.Debug($"voice clone: hearing failed {e.Message}"); }
+ text = text?.Trim() ?? "";
+ if (text.Length < 6) return (Outcome.NotHeard, text);
+ var pace = VoicePace.Pace(text, VoicePace.Samples(wav), 16000);
+ Log.Debug($"voice clone: {text.Length} chars, {seconds:F1} s, pace {(pace is { } p ? p.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) : "-")}/s");
+ if (pace is { } q && VoicePace.IsSlow(text, q)) return (Outcome.Slow, text);
+ return (Outcome.Ready, text);
+ }
+
+ /// The passage to read, in the user's own language (Voices.swift › VoiceReference.passage).
+ public static string Passage(string language) => VoiceCatalog.Key(language) switch
+ {
+ "zh" => "大家好,我是这次会议的主持人。今天我们主要讨论新产品的上线计划,包括时间安排、测试范围和市场推广。请大家先看一下屏幕上的议程。",
+ "ja" => "皆さん、こんにちは。今日の会議では、新製品の発売計画について話し合います。スケジュール、テストの範囲、そしてマーケティングについて順番に確認しましょう。",
+ _ => "Hello everyone, thanks for joining. Today we'll walk through the launch plan for the new product: the schedule, what we still need to test, and how we'll tell people about it. Let's start with the agenda on the screen.",
+ };
+}
diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.cs
index 3a7d351..bf5f012 100644
--- a/windows/src/Cicada/App.cs
+++ b/windows/src/Cicada/App.cs
@@ -65,6 +65,8 @@ sealed class Controller
public readonly FolderExporter FolderExport;
/// 分享…: the share service, its device key and the links made (sealed files, never the record).
public readonly ShareClient Sharing = new(new DpapiProtector(), "windows", Version);
+ /// 我自己的声音: the recording Ming clones the user's voice from, sealed like the keys.
+ public readonly VoiceReference OwnVoice = new(new DpapiProtector());
/// Dev (`silentlisten`): the language `heard` lines are in.
public string? SilentLang;
/// Started with Windows (--background): stay in the tray. Opened by hand, the main window shows.
@@ -135,6 +137,7 @@ sealed class Controller
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(); });
+ Speak.Reference = OwnVoice;
Listen.Voiceprint = new WinVoiceprint();
// No voices on the room side: its numbers would collide with the PC's.
// The talk key's echo check: the meeting playing through a press is sent back otherwise.
@@ -948,7 +951,7 @@ sealed class Controller
Changed();
try
{
- var chosen = VoiceCatalog.Chosen(Settings, language, Ling.Config, Ling.Speaks, WindowsVoice.Has(language));
+ var chosen = Speak.ChosenVoice(language);
var voiced = await Speak.Voice(VoiceCatalog.Sample(language), language, speaker);
result = speaker.Stopped ? PreviewResult.Stopped
: !voiced ? (WindowsVoice.Has(language) ? PreviewResult.Failed : PreviewResult.NoVoice)
@@ -964,6 +967,78 @@ sealed class Controller
return result;
}
+ // MARK: 我自己的声音
+
+ /// The microphone a recording for the user's own voice comes from: the talk key's.
+ public Endpoints.Device? OwnVoiceMic() => TalkMic();
+
+ /// What a recording says, as the hear model (Ming on Ling) hears it; null when it heard nothing.
+ public async Task<string?> Transcribe(byte[] wav) =>
+ (await Translator.Hear(wav, Speak.Target, Speak.MyLanguage, Priority.Speak))?.Original;
+
+ /// Plays a recording (16 kHz mono WAV) on the speakers; 停止 is StopPreview.
+ public async Task PlayRecording(byte[] wav)
+ {
+ previewing?.Stop();
+ var speaker = new DeviceSpeaker(() => Endpoints.Default(Endpoints.Flow.Render));
+ if (!speaker.Ready) return;
+ previewing = speaker;
+ try
+ {
+ speaker.Begin(Segmenter.Rate);
+ speaker.Write(wav.Length > 44 ? wav[44..] : wav);
+ await speaker.End();
+ }
+ finally { if (previewing == speaker) previewing = null; }
+ }
+
+ /// The review's 用你的声音说…: the language's sample line in a voice cloned from a recording not
+ /// yet kept, on the speakers. True once something played.
+ public async Task<bool> PreviewOwnVoice(byte[] wav, string text, string language)
+ {
+ previewing?.Stop();
+ var speaker = new DeviceSpeaker(() => Endpoints.Default(Endpoints.Flow.Render));
+ if (!speaker.Ready || !Ling.Clones) return false;
+ previewing = speaker;
+ Changed();
+ int chunks = 0;
+ try
+ {
+ var reference = ("data:audio/wav;base64," + Convert.ToBase64String(wav), text);
+ await foreach (var pcm in Ling.Speech(VoiceCatalog.Sample(language), null, VoiceCatalog.MingLanguage(language), reference))
+ {
+ if (speaker.Stopped) break;
+ if (chunks++ == 0) speaker.Begin(24000);
+ speaker.Write(pcm);
+ }
+ if (chunks > 0) await speaker.End();
+ }
+ catch (LingException e) { Log.Debug($"preview: cloned voice failed {e.Message}"); }
+ finally { if (previewing == speaker) previewing = null; Changed(); }
+ Log.Debug($"preview: cloned voice {language} {(chunks > 0 ? "played" : "silent")}");
+ return chunks > 0;
+ }
+
+ /// Keeps a recording as the user's own voice and uses it for `language` (VoiceCloneSheet.save).
+ public void SaveOwnVoice(byte[] wav, string text, string language)
+ {
+ OwnVoice.Save(wav, text);
+ Settings.SpeakVoices[VoiceCatalog.Key(language)] = VoiceCatalog.CloneId;
+ Settings.Save();
+ Log.Debug($"voice clone saved {(wav.Length - 44) / 32000.0:F0} s");
+ Changed();
+ }
+
+ /// 删除: the recording goes, and every language that used it gets its default back.
+ public void RemoveOwnVoice()
+ {
+ OwnVoice.Remove();
+ foreach (var k in Settings.SpeakVoices.Where(p => p.Value == VoiceCatalog.CloneId).Select(p => p.Key).ToList()) Settings.SpeakVoices.Remove(k);
+ Settings.Save();
+ Log.Debug("voice clone removed");
+ Changed();
+ }
+
// MARK: Windows
/// The tray icon while listening: the notes window comes and goes.
@@ -1376,6 +1451,9 @@ sealed class Controller
["heard"] = Speak.Heard,
["speakProblem"] = Speak.Problem,
["voice"] = Speak.LastVoice,
+ ["ownVoice"] = OwnVoice.Exists ? Math.Round(OwnVoice.Duration, 1) : null,
+ ["ownVoiceReady"] = Speak.CloneReady,
+ ["voiceFor"] = Speak.ChosenVoice(Speak.Target),
["cable"] = Endpoints.Cable() is not null,
["autostart"] = AutoStart.Enabled,
["ending"] = Ending is { } p ? $"{EndingTitle(p)} · {EndingLeft(p)}" : null,
@@ -1403,6 +1481,7 @@ sealed class Controller
/// updatefeed <url or file> | checkupdate
/// calls <program=name,…>|none|real | realcalls | endtimes <silence> <countdown> <grace>|off | endkeep
/// provider ling|openrouter|zenmux|custom | ai-model hear|text|voice <id> (设置 › AI 服务; no id: the recommended)
+/// ownvoice <wav>[|<text>] | ownvoice remove | ownvoice dialog [<wav>] | voice <lang>=<id> (我自己的声音)
/// open <id> [transcript] | play <seconds>|toggle|speed|follow|row <i> | recordaudio on|off (保存会议录音 and 回放)
/// aacencode <wav>|<out.aac> | aacrewrap <in.aac>|<out.m4a>[|<seconds>]
/// ai-check | ai-check-sim <reason|lowBalance|off> (unreachable, invalidKey, noCredit, noModel, deaf, busy…)
@@ -1485,6 +1564,37 @@ static class DebugServer
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;
+ // 我自己的声音 without a microphone: "ownvoice <wav>[|<what it says>]" checks a recording as
+ // the dialog does (heard by Ming unless the words are given) and keeps it; "ownvoice remove"
+ // is 删除; "ownvoice dialog [<wav>]" opens the recording dialog (with a WAV: as if just read).
+ case "ownvoice":
+ {
+ if (arg == "remove") { app.RemoveOwnVoice(); return new JsonObject { ["ownVoice"] = app.OwnVoice.Exists }; }
+ if (arg.StartsWith("dialog"))
+ {
+ var file = arg[6..].Trim();
+ app.Dispatcher().BeginInvoke(() => VoiceCloneDialog.Open(app, app.Speak.Target, file.Length > 0 ? Wav.Bytes(Wav.Read(file)) : null));
+ break;
+ }
+ var p = arg.Split('|', 2);
+ var wav = Wav.Bytes(Wav.Read(p[0]));
+ var given = p.Length > 1 ? p[1].Trim() : null;
+ var target = app.Speak.Target;
+ _ = Task.Run(async () =>
+ {
+ var (outcome, text) = await VoiceCloneCheck.Check(wav, w => given is not null ? Task.FromResult<string?>(given) : app.Transcribe(w));
+ Log.Debug($"ownvoice: {outcome}");
+ if (outcome == VoiceCloneCheck.Outcome.Ready) app.Dispatcher().Invoke(() => app.SaveOwnVoice(wav, text, target));
+ });
+ break;
+ }
+ // voice <lang>=<id>: 线上的人听到的声音 for a language ("voice en=clone", "voice zh=ming:灵小雅").
+ case "voice":
+ {
+ var kv = arg.Split('=', 2);
+ if (kv.Length == 2) { app.Settings.SpeakVoices[VoiceCatalog.Key(kv[0])] = kv[1]; app.Settings.Save(); app.SettingsChanged(); }
+ return new JsonObject { ["voice"] = app.Speak.ChosenVoice(kv[0]), ["clone"] = app.Speak.CloneReady };
+ }
case "provider": app.SetAIProvider(arg); break;
// switchtoling: the 改用 Ling on a status line (logs why when it isn't offered).
case "switchtoling": Log.Debug($"switchtoling offered={app.CanSwitchToLing}"); app.SwitchToLing(); break;
diff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.cs
index 86b5b4b..1955bdc 100644
--- a/windows/src/Cicada/SettingsWindow.cs
+++ b/windows/src/Cicada/SettingsWindow.cs
@@ -50,7 +50,8 @@ sealed partial class SettingsWindow : Window
Content = Ui.Frameless(this, grid);
scroll.ScrollChanged += (_, e) => { if (e.ViewportWidthChange != 0 && scroll.Content is FrameworkElement p) p.Width = PageWidth(); };
app.Ling.Changed += OnLingChanged;
- Closed += (_, _) => app.Ling.Changed -= OnLingChanged;
+ app.OwnVoice.Changed += OnLingChanged;
+ Closed += (_, _) => { app.Ling.Changed -= OnLingChanged; app.OwnVoice.Changed -= OnLingChanged; };
// While a talk key is being chosen no key reaches any app: leaving the window ends it.
Deactivated += (_, _) => StopChoosingKey();
Closed += (_, _) => { if (choosingKey) app.StopChoosingTalkKey(); };
@@ -268,9 +269,9 @@ sealed partial class SettingsWindow : Window
: Ui.Button(L("安装"), () => _ = InstallCable(), Ui.Kind.Primary, height: 32);
var target = app.Speak.Target;
var config = app.Ling.Config;
- var voices = VoiceCatalog.Options(target, config, app.WindowsVoice.Has(target))
- .Select(v => (v.Id, v.Id == VoiceCatalog.SystemId ? L("Windows 自带") : v.Tags.Length == 0 ? v.Name : $"{v.Name} · {string.Join(" · ", v.Tags.Split(" · ").Select(L))}")).ToList();
- var chosen = VoiceCatalog.Chosen(s, target, config, app.Ling.Speaks, app.WindowsVoice.Has(target));
+ var voices = VoiceCatalog.Options(target, config, app.WindowsVoice.Has(target), app.Speak.CloneReady)
+ .Select(v => (v.Id, v.Id == VoiceCatalog.SystemId ? L("Windows 自带") : v.Id == VoiceCatalog.CloneId ? L(v.Name) : v.Tags.Length == 0 ? v.Name : $"{v.Name} · {string.Join(" · ", v.Tags.Split(" · ").Select(L))}")).ToList();
+ var chosen = app.Speak.ChosenVoice(target);
var voice = Ui.Row(8,
Ui.Choice(voices, chosen, v => { s.SpeakVoices[VoiceCatalog.Key(target)] = v; previewNote = null; Save(); Render(); }, 280),
Ui.Button(app.Previewing ? L("停止") : L("试听"), () => { if (app.Previewing) app.StopPreview(); else _ = RunPreview(); }, height: 32));
@@ -290,7 +291,8 @@ sealed partial class SettingsWindow : Window
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(); })),
note is null ? Card(null, LF("线上的人听到的声音(%@)", Ui.TargetName(target)), null, voice)
- : Ui.Stack(0, Card(null, LF("线上的人听到的声音(%@)", Ui.TargetName(target)), null, voice), PreviewNoteBox(note.Value)));
+ : Ui.Stack(0, Card(null, LF("线上的人听到的声音(%@)", Ui.TargetName(target)), null, voice), PreviewNoteBox(note.Value)),
+ OwnVoiceCard(target, chosen == VoiceCatalog.CloneId));
yield return Label(L("麦克风"));
var mic = Card(null, L("译文送进会议"), cable ? L("在会议软件里把麦克风选成 CABLE Output") : L("需要装免费的 VB-Cable;装的时候 Windows 会请你确认"), cableControl);
if (cable && Endpoints.SpeakerIsCable())
@@ -344,6 +346,48 @@ sealed partial class SettingsWindow : Window
return box;
}
+ /// 我自己的声音 (VoicePicker.swift › cloneRow), under the voice: 录制 before there is a recording;
+ /// then its length and how close it will sound, with 重录 and 删除; greyed with 去换成 Ling on a
+ /// service that can't clone. Choosing it is the voice menu's last item.
+ FrameworkElement OwnVoiceCard(string target, bool chosen)
+ {
+ var own = app.OwnVoice;
+ if (!app.Ling.Config.Provider.Clones)
+ {
+ var title = Ui.Text(L("我自己的声音"), 14, Palette.Secondary);
+ return CardWith(title, L("只有 Ling 能用你自己的声音"), Ui.Button(L("去换成 Ling"), () => Show("ai"), height: 32));
+ }
+ if (own.Exists)
+ {
+ var note = own.SavedIsSlow ? L("读得偏慢")
+ : VoiceCatalog.Key(app.Speak.MyLanguage) == VoiceCatalog.Key(target) ? L("最像你") : L("会带你的口音");
+ var buttons = Ui.Row(8,
+ Ui.Button(L("重录"), () => RecordOwnVoice(target), height: 32),
+ Ui.Button(L("删除"), () => { app.RemoveOwnVoice(); Render(); }, height: 32));
+ var title = Ui.Text(L("我自己的声音"), 14, Palette.Ink, chosen ? Palette.Strong : (FontWeight?)null);
+ return CardWith(title, LF("已录 %lld 秒 · %@", (int)Math.Round(own.Duration), note), buttons);
+ }
+ var record = Ui.Button(L("录制"), () => RecordOwnVoice(target), Ui.Kind.Primary, height: 32);
+ record.IsEnabled = app.Ling.Clones;
+ return CardWith(Ui.Text(L("我自己的声音"), 14, Palette.Ink), L("录 15 秒原声,对方听到你的音色,晚约 3 秒"), record);
+ }
+
+ /// A Card whose title is already a TextBlock (greyed or bold).
+ static FrameworkElement CardWith(TextBlock title, string description, FrameworkElement control)
+ {
+ var card = (DockPanel)Card(null, "", description, control);
+ var text = (StackPanel)card.Children[^1];
+ text.Children.RemoveAt(0);
+ text.Children.Insert(0, title);
+ return card;
+ }
+
+ void RecordOwnVoice(string target)
+ {
+ if (VoiceCloneDialog.Open(app, target, null)) previewNote = null;
+ Render();
+ }
+
// 试听's result, shown under the voice until another voice is picked or 试听 is pressed again.
(string Title, string Help, bool VoiceSettings)? previewNote;
diff --git a/windows/src/Cicada/Strings/en.lproj/Windows.strings b/windows/src/Cicada/Strings/en.lproj/Windows.strings
index d940b5a..2da0c7d 100644
--- a/windows/src/Cicada/Strings/en.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/en.lproj/Windows.strings
@@ -364,3 +364,4 @@
"在 Windows 安全中心里允许知了,或换个文件夹" = "Allow Cicada in Windows Security, or pick another folder";
"换个文件夹,或在它的属性里允许写入" = "Pick another folder, or allow writing in its Properties";
"在文件资源管理器中显示" = "Show in File Explorer";
+"听起来不像或有杂音?换个安静的地方重录一次。录音仅保存在本机,可随时删除。" = "Doesn't sound like you, or noisy? Record again somewhere quiet. The recording stays on this PC and can be deleted anytime.";
diff --git a/windows/src/Cicada/Strings/ja.lproj/Windows.strings b/windows/src/Cicada/Strings/ja.lproj/Windows.strings
index 1098860..9d89068 100644
--- a/windows/src/Cicada/Strings/ja.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/ja.lproj/Windows.strings
@@ -364,3 +364,4 @@
"在 Windows 安全中心里允许知了,或换个文件夹" = "Windows セキュリティで Cicada を許可するか、別のフォルダを選んでください";
"换个文件夹,或在它的属性里允许写入" = "別のフォルダを選ぶか、フォルダのプロパティで書き込みを許可してください";
"在文件资源管理器中显示" = "エクスプローラーで表示";
+"听起来不像或有杂音?换个安静的地方重录一次。录音仅保存在本机,可随时删除。" = "似ていない、またはノイズがありますか?静かな場所で録り直してください。録音はこのPCにのみ保存され、いつでも削除できます。";
diff --git a/windows/src/Cicada/Strings/ko.lproj/Windows.strings b/windows/src/Cicada/Strings/ko.lproj/Windows.strings
index 14b0357..7793559 100644
--- a/windows/src/Cicada/Strings/ko.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/ko.lproj/Windows.strings
@@ -364,3 +364,4 @@
"在 Windows 安全中心里允许知了,或换个文件夹" = "Windows 보안에서 Cicada를 허용하거나 다른 폴더를 고르세요";
"换个文件夹,或在它的属性里允许写入" = "다른 폴더를 고르거나 폴더 속성에서 쓰기를 허용하세요";
"在文件资源管理器中显示" = "파일 탐색기에서 보기";
+"听起来不像或有杂音?换个安静的地方重录一次。录音仅保存在本机,可随时删除。" = "내 목소리 같지 않거나 잡음이 있나요? 조용한 곳에서 다시 녹음해 보세요. 녹음은 이 PC에만 저장되며 언제든 삭제할 수 있습니다.";
diff --git a/windows/src/Cicada/VoiceCloneDialog.cs b/windows/src/Cicada/VoiceCloneDialog.cs
new file mode 100644
index 0000000..d6a8e1f
--- /dev/null
+++ b/windows/src/Cicada/VoiceCloneDialog.cs
@@ -0,0 +1,306 @@
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Threading;
+using static Cicada.Strings;
+
+namespace Cicada.App;
+
+/// 我自己的声音's recording, the Mac's VoiceCloneSheet in a Windows 11 dialog: read a passage for
+/// 10–15 s (it stops by itself at 15) → Ming hears what was said → listen to the recording and to the
+/// clone speaking the room's language → 用这个声音 keeps it. Nothing is kept until then.
+sealed class VoiceCloneDialog
+{
+ enum Phase { Idle, Recording, Checking, Failed, Ready }
+
+ readonly Controller app;
+ readonly string target;
+ readonly Window window;
+ readonly Border body = new() { Padding = new Thickness(24) };
+ Phase phase;
+ string? failure;
+ byte[]? wav;
+ string transcript = "";
+ DeviceRecorder? recorder;
+ DispatcherTimer? timer;
+ DateTime started;
+ double seconds;
+ bool saved, playingOriginal, playingClone;
+ // Updated ten times a second while recording, without rebuilding the dialog.
+ ColumnDefinition? levelOn, levelOff, timeOn, timeOff;
+ TextBlock? clock;
+
+ VoiceCloneDialog(Controller app, string target, Window? owner)
+ {
+ this.app = app;
+ this.target = target;
+ window = new Window
+ {
+ Owner = owner, WindowStyle = WindowStyle.None, AllowsTransparency = true, Background = Brushes.Transparent,
+ ResizeMode = ResizeMode.NoResize, ShowInTaskbar = false, SizeToContent = SizeToContent.Height, Width = 520 + 32,
+ WindowStartupLocation = owner is null ? WindowStartupLocation.CenterScreen : WindowStartupLocation.CenterOwner,
+ Topmost = owner is null, FontFamily = Palette.Font, Title = L("录制你的声音"),
+ Content = new Border
+ {
+ Margin = new Thickness(16), Background = Palette.Surface, BorderBrush = Palette.Line, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(16),
+ Effect = new System.Windows.Media.Effects.DropShadowEffect { BlurRadius = 32, ShadowDepth = 8, Opacity = 0.25 },
+ Child = body,
+ },
+ };
+ window.MouseLeftButtonDown += (_, e) => { if (e.ButtonState == MouseButtonState.Pressed) try { window.DragMove(); } catch { } };
+ window.KeyDown += (_, e) => { if (e.Key == Key.Escape) window.Close(); };
+ window.Closed += (_, _) => { StopRecording(); app.StopPreview(); };
+ }
+
+ /// Shows the dialog; true when a recording was kept. `recorded`: a WAV taken as just read (the
+ /// debug pipe's `ownvoice dialog <wav>`, for a machine without a microphone).
+ public static bool Open(Controller app, string target, byte[]? recorded)
+ {
+ var d = new VoiceCloneDialog(app, target, app.OpenSettings);
+ d.Render();
+ if (recorded is not null) d.window.Loaded += (_, _) => _ = d.Check(recorded);
+ d.window.ShowDialog();
+ return d.saved;
+ }
+
+ string MyLanguage => app.Speak.MyLanguage;
+
+ void Render()
+ {
+ levelOn = levelOff = timeOn = timeOff = null; clock = null;
+ body.Child = phase == Phase.Ready ? Review() : Record();
+ }
+
+ // MARK: Reading
+
+ FrameworkElement Record()
+ {
+ var stack = new StackPanel();
+ stack.Children.Add(Ui.Text(L("录制你的声音"), 20, Palette.Ink, FontWeights.Bold));
+ stack.Children.Add(Spaced(Ui.Helper(L("请用平时开会的自然语气朗读以下段落,约 15 秒,在安静环境下录制效果最佳。")), 6));
+ var passage = Ui.Text(VoiceCloneCheck.Passage(MyLanguage), 15, Palette.Ink);
+ passage.LineHeight = 26;
+ stack.Children.Add(Spaced(new Border { Background = Palette.Mica, CornerRadius = new CornerRadius(10), Padding = new Thickness(16, 14, 16, 14), Child = passage }, 16));
+ stack.Children.Add(Spaced(Ui.Text(L("这是我自己的声音。只在我说话时用它替我翻译。"), 12, Palette.Secondary), 12));
+
+ // The level and the time read so far; the range under them.
+ var level = Bar(Palette.Live, 6, out levelOn, out levelOff);
+ clock = Ui.Text(Clock(seconds), 13, Palette.Ink, FontWeights.SemiBold, wrap: false);
+ clock.Margin = new Thickness(12, 0, 0, 0);
+ var meter = new DockPanel { Margin = new Thickness(0, 16, 0, 0) };
+ DockPanel.SetDock(clock, Dock.Right);
+ meter.Children.Add(clock);
+ meter.Children.Add(level);
+ stack.Children.Add(meter);
+ stack.Children.Add(Spaced(Bar(Palette.Live, 4, out timeOn, out timeOff, Palette.Subtle), 8));
+ Show(0, Math.Min(1, seconds / VoiceReference.MaxSeconds));
+ stack.Children.Add(Spaced(Ui.Text(LF("%lld–%lld 秒", (int)VoiceReference.MinSeconds, (int)VoiceReference.MaxSeconds), 12, Palette.Tertiary), 6));
+ if (phase == Phase.Failed && failure is not null) stack.Children.Add(Spaced(Ui.Text(failure, 12, Palette.Danger), 10));
+
+ FrameworkElement action = phase switch
+ {
+ Phase.Recording => Ui.Button(L("读完了"), () => _ = Finish(), Ui.Kind.Primary),
+ Phase.Checking => Centered(Ui.Text(L("正在听写…"), 13, Palette.Secondary, wrap: false)),
+ _ => Ui.Button(phase == Phase.Idle ? L("开始录") : L("再录一次"), Start, Ui.Kind.Primary),
+ };
+ stack.Children.Add(Spaced(Buttons(Ui.Button(L("取消"), window.Close), action), 24));
+ return stack;
+ }
+
+ void Start()
+ {
+ app.StopPreview();
+ failure = null;
+ seconds = 0;
+ if (app.OwnVoiceMic() is not { } mic) { Fail(L("麦克风没收到声音,请检查麦克风权限")); return; }
+ var r = new DeviceRecorder(mic.Id);
+ r.Start();
+ if (r.Error is { } err)
+ {
+ Fail(err == "denied" ? L("麦克风没收到声音,请检查麦克风权限") : LF("无法打开麦克风:%@", err));
+ return;
+ }
+ recorder = r;
+ started = DateTime.UtcNow;
+ phase = Phase.Recording;
+ Log.Debug($"voice clone: recording from {mic.Name}");
+ Render();
+ timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) };
+ timer.Tick += (_, _) =>
+ {
+ if (recorder is not { } rec) return;
+ seconds = (DateTime.UtcNow - started).TotalSeconds;
+ Show(rec.Level, Math.Min(1, seconds / VoiceReference.MaxSeconds));
+ if (seconds >= VoiceReference.MaxSeconds) _ = Finish();
+ };
+ timer.Start();
+ }
+
+ short[] StopRecording()
+ {
+ timer?.Stop();
+ timer = null;
+ var pcm = recorder?.Stop() ?? [];
+ recorder = null;
+ return pcm;
+ }
+
+ async Task Finish()
+ {
+ if (phase != Phase.Recording) return;
+ var pcm = StopRecording();
+ await Check(Wav.Bytes(pcm));
+ }
+
+ /// The Mac's VoiceRecorder.finish: long enough, heard, and read at a meeting's pace.
+ async Task Check(byte[] recorded)
+ {
+ wav = recorded;
+ seconds = Math.Max(0, recorded.Length - 44) / 32000.0;
+ phase = Phase.Checking;
+ Render();
+ var (outcome, text) = await VoiceCloneCheck.Check(recorded, app.Transcribe);
+ transcript = text;
+ Log.Debug($"voice clone: {outcome}");
+ switch (outcome)
+ {
+ case VoiceCloneCheck.Outcome.TooShort: Fail(LF("录音太短了,请至少朗读 %lld 秒", (int)VoiceReference.MinSeconds)); break;
+ case VoiceCloneCheck.Outcome.NotHeard: Fail(L("没听清录音内容,请换个安静的地方再录一次")); break;
+ case VoiceCloneCheck.Outcome.Slow: Fail(L("读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次")); break;
+ default: phase = Phase.Ready; Render(); break;
+ }
+ }
+
+ void Fail(string why)
+ {
+ StopRecording();
+ failure = why;
+ phase = Phase.Failed;
+ Render();
+ }
+
+ // MARK: Listening
+
+ FrameworkElement Review()
+ {
+ var stack = new StackPanel();
+ // A way out without keeping it: this step's two buttons are 重录 and 用这个声音.
+ var close = Ui.IconButton(Icons.Close, L("关闭"), window.Close, Palette.Secondary, size: 32, iconSize: 14);
+ close.VerticalAlignment = VerticalAlignment.Top;
+ close.Margin = new Thickness(8, -4, -8, 0);
+ var header = new DockPanel();
+ DockPanel.SetDock(close, Dock.Right);
+ header.Children.Add(close);
+ header.Children.Add(Ui.Text(L("录好了,先听听像不像"), 20, Palette.Ink, FontWeights.Bold));
+ stack.Children.Add(header);
+ stack.Children.Add(Spaced(Ui.Helper(LF("%lld 秒 · 识别出的文字会与录音一起用于学习你的音色", (int)Math.Round(seconds))), 6));
+ var rows = new StackPanel();
+ rows.Children.Add(Row(playingOriginal, accent: false, L("你的原声"), transcript, null, PlayOriginal));
+ rows.Children.Add(Row(playingClone, accent: true, LF("用你的声音说%@", Ui.TargetName(target)), VoiceCatalog.Sample(target), L("对方会听到这个"), PlayClone));
+ stack.Children.Add(Spaced(new Border { BorderBrush = Palette.Line, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(10), ClipToBounds = true, Child = rows }, 16));
+ if (!app.Ling.Clones) stack.Children.Add(Spaced(Ui.Text(L("需先在“AI 服务”中填入 Ling key,才能使用你自己的声音。"), 12, Palette.Danger), 10));
+ stack.Children.Add(Spaced(Ui.Text(L("听起来不像或有杂音?换个安静的地方重录一次。录音仅保存在本机,可随时删除。"), 12, Palette.Tertiary), 12));
+ var use = Ui.Button(L("用这个声音"), Save, Ui.Kind.Primary);
+ use.IsEnabled = app.Ling.Clones;
+ stack.Children.Add(Spaced(Buttons(Ui.Button(L("重录"), () => { app.StopPreview(); Start(); }), use), 24));
+ return stack;
+ }
+
+ FrameworkElement Row(bool playing, bool accent, string title, string detail, string? tag, Action play)
+ {
+ var button = Ui.IconButton(playing ? Icons.Stop : Icons.Play, playing ? L("停止") : L("试听"), play, accent ? Brushes.White : Palette.Ink, size: 32, iconSize: 12, fill: true);
+ button.Background = accent ? Palette.Live : Palette.Subtle;
+ button.VerticalAlignment = VerticalAlignment.Top;
+ var head = Ui.Row(8, Ui.Text(title, 14, Palette.Ink, FontWeights.SemiBold, wrap: false));
+ if (tag is not null) head.Children.Add(Ui.Badge(tag, Palette.AccentPale, Palette.AccentText));
+ var text = Ui.Stack(4, head, Ui.Text(detail, 12, Palette.Secondary));
+ text.Margin = new Thickness(12, 0, 0, 0);
+ var dock = new DockPanel();
+ DockPanel.SetDock(button, Dock.Left);
+ dock.Children.Add(button);
+ dock.Children.Add(text);
+ return new Border
+ {
+ Padding = new Thickness(16, 14, 16, 14), Child = dock,
+ Background = accent ? Palette.AccentPale : Palette.Surface,
+ BorderBrush = Palette.Line, BorderThickness = new Thickness(0, accent ? 1 : 0, 0, 0),
+ };
+ }
+
+ async void PlayOriginal()
+ {
+ if (wav is null) return;
+ if (playingOriginal || playingClone) { app.StopPreview(); return; }
+ playingOriginal = true; Render();
+ try { await app.PlayRecording(wav); } finally { playingOriginal = false; Render(); }
+ }
+
+ async void PlayClone()
+ {
+ if (wav is null) return;
+ if (playingOriginal || playingClone) { app.StopPreview(); return; }
+ playingClone = true; Render();
+ try { await app.PreviewOwnVoice(wav, transcript, target); } finally { playingClone = false; Render(); }
+ }
+
+ void Save()
+ {
+ if (wav is null) return;
+ app.StopPreview();
+ try { app.SaveOwnVoice(wav, transcript, target); saved = true; }
+ catch (Exception e) { Log.Debug($"voice clone save failed {e.GetType().Name}"); }
+ window.Close();
+ }
+
+ // MARK: Pieces
+
+ static FrameworkElement Spaced(FrameworkElement e, double top) { e.Margin = new Thickness(0, top, 0, 0); return e; }
+
+ static FrameworkElement Centered(FrameworkElement e) { e.HorizontalAlignment = HorizontalAlignment.Center; e.VerticalAlignment = VerticalAlignment.Center; return e; }
+
+ static string Clock(double s) => $"{(int)s / 60}:{(int)s % 60:00}";
+
+ /// A bar filled from the left by two star columns; Show sets the share.
+ static Grid Bar(Brush fill, double height, out ColumnDefinition on, out ColumnDefinition off, Brush? track = null)
+ {
+ var grid = new Grid { Height = height, VerticalAlignment = VerticalAlignment.Center };
+ on = new ColumnDefinition { Width = new GridLength(0, GridUnitType.Star) };
+ off = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) };
+ grid.ColumnDefinitions.Add(on);
+ grid.ColumnDefinitions.Add(off);
+ var back = new Border { Background = track ?? Palette.Subtle, CornerRadius = new CornerRadius(height / 2) };
+ Grid.SetColumnSpan(back, 2);
+ grid.Children.Add(back);
+ grid.Children.Add(new Border { Background = fill, CornerRadius = new CornerRadius(height / 2) });
+ return grid;
+ }
+
+ void Show(float level, double elapsed)
+ {
+ if (levelOn is not null && levelOff is not null)
+ {
+ levelOn.Width = new GridLength(Math.Clamp(level, 0, 1), GridUnitType.Star);
+ levelOff.Width = new GridLength(1 - Math.Clamp(level, 0, 1), GridUnitType.Star);
+ }
+ if (timeOn is not null && timeOff is not null)
+ {
+ timeOn.Width = new GridLength(elapsed, GridUnitType.Star);
+ timeOff.Width = new GridLength(1 - elapsed, GridUnitType.Star);
+ }
+ if (clock is not null) clock.Text = Clock(seconds);
+ }
+
+ /// Two equal buttons, the main one on the right (Dialogs.Show's band).
+ static Grid Buttons(FrameworkElement cancel, FrameworkElement primary)
+ {
+ var grid = new Grid();
+ grid.ColumnDefinitions.Add(new ColumnDefinition());
+ grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(8) });
+ grid.ColumnDefinitions.Add(new ColumnDefinition());
+ Grid.SetColumn(primary, 2);
+ grid.Children.Add(cancel);
+ grid.Children.Add(primary);
+ return grid;
+ }
+}
diff --git a/windows/src/Cicada/Wasapi.cs b/windows/src/Cicada/Wasapi.cs
index efce81a..725d875 100644
--- a/windows/src/Cicada/Wasapi.cs
+++ b/windows/src/Cicada/Wasapi.cs
@@ -266,6 +266,8 @@ sealed class DeviceRecorder
Thread? thread;
volatile bool running;
public string? Error { get; private set; }
+ /// The last packet's peak, 0–1 (scaled as the Mac's recorder meter): for a level bar.
+ public volatile float Level;
public DeviceRecorder(string id) { this.id = id; }
@@ -310,6 +312,9 @@ sealed class DeviceRecorder
var buf = new short[frames];
if ((flags & 0x2) == 0) Marshal.Copy(data, buf, 0, (int)frames);
cap.ReleaseBuffer(frames);
+ int peak = 0;
+ foreach (var v in buf) peak = Math.Max(peak, Math.Abs((int)v));
+ Level = Math.Min(1f, peak / 32768f * 2.5f);
lock (samples) samples.AddRange(buf);
}
}
diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.cs
index 47fc491..c992156 100644
--- a/windows/tests/Cicada.Tests/Program.cs
+++ b/windows/tests/Cicada.Tests/Program.cs
@@ -2891,6 +2891,136 @@ static class Tests
Equal("ming:US_Emma", VoiceCatalog.Chosen(system, "en", ling, false, windowsHasIt: false), "even before the service is checked");
}
+ // MARK: 我自己的声音
+
+ public static void KeepsTheOwnVoiceRecordingSealed()
+ {
+ var folder = Path.Combine(Paths.Root, "voice-test");
+ var r = new VoiceReference(new FlipProtector(), folder);
+ Check(!r.Exists && r.Reference() is null, "nothing recorded yet");
+ var wav = Wav.Bytes(new short[16000 * 12]);
+ int changes = 0;
+ r.Changed += () => changes++;
+ r.Save(wav, " 大家好,我是这次会议的主持人。 ");
+ Check(r.Exists, "saved");
+ Equal(12.0, r.Duration, "its length");
+ Equal("大家好,我是这次会议的主持人。", r.Text, "its words, trimmed");
+ Check(!File.ReadAllText(r.AudioFile).Contains("RIFF") && File.ReadAllText(r.AudioFile).StartsWith("dpapi:"), "sealed on disk, not a plain WAV");
+ Check(!File.ReadAllText(r.TextFile).Contains("主持人"), "the words too");
+ var (audio, text) = r.Reference()!.Value;
+ Check(audio.StartsWith("data:audio/wav;base64,") && Convert.FromBase64String(audio[22..]).SequenceEqual(wav), "Ming gets the WAV back as a data URI");
+ Equal("大家好,我是这次会议的主持人。", text, "with what it says");
+ Equal(true, new VoiceReference(new FlipProtector(), folder).Exists, "read back by a fresh instance");
+ r.Remove();
+ Check(!r.Exists && !Directory.Exists(folder), "删除 takes the folder");
+ Equal(2, changes, "saved and removed are announced");
+ }
+
+ sealed class FlipProtector : IKeyProtector
+ {
+ public string Tag => "flip";
+ public byte[] Protect(byte[] data) => data.Select(b => (byte)~b).ToArray();
+ public byte[] Unprotect(byte[] data) => data.Select(b => (byte)~b).ToArray();
+ }
+
+ public static void SendsTheOwnVoiceAsAReference()
+ {
+ var ling = new AppSettings().AIConfig();
+ var cloned = LingClient.SpeechBody(ling, "Hello", "US_Emma", "ja", ("data:audio/wav;base64,AAAA", "大家好"));
+ var refs = cloned["references"]!.AsArray();
+ Equal(1, refs.Count, "one reference");
+ Equal(("data:audio/wav;base64,AAAA", "大家好"), (refs[0]!["audio"]!.GetValue<string>(), refs[0]!["text"]!.GetValue<string>()), "the clip and its words");
+ Check(cloned["voice"] is null, "no built-in voice beside it");
+ Equal("ja", cloned["language_id"]!.GetValue<string>(), "language_id still sent");
+ Check(cloned["stream"]!.GetValue<bool>() && cloned["sample_rate"]!.GetValue<int>() == 24000, "streamed as Ming's other voices");
+ var plain = LingClient.SpeechBody(ling, "Hello", "US_Emma", null);
+ Check(plain["references"] is null && plain["voice"]!.GetValue<string>() == "US_Emma", "a built-in voice sends no reference");
+ var zen = LingClient.SpeechBody(new AppSettings { AiProvider = "zenmux" }.AIConfig(), "Hello", null, null, ("data:x", "y"));
+ Check(zen["references"] is null, "only Ling clones");
+ }
+
+ public static void OwnVoiceFallsBackWithoutItsRecordingOrLing()
+ {
+ var ling = new AppSettings().AIConfig();
+ var zen = new AppSettings { AiProvider = "zenmux" }.AIConfig();
+ var s = new AppSettings { SpeakVoices = { ["en"] = "clone" } };
+ Equal("ming:US_Emma,ming:UK_George,ming:UK_Charlotte,system,clone", string.Join(",", VoiceCatalog.Options("en", ling, clone: true).Select(v => v.Id)), "offered last, once recorded");
+ Check(!VoiceCatalog.Options("en", ling).Any(v => v.Id == "clone"), "not before");
+ Equal("clone", VoiceCatalog.Chosen(s, "en", ling, true, clone: true), "used when recorded on Ling");
+ Equal("ming:US_Emma", VoiceCatalog.Chosen(s, "en", ling, true, clone: false), "the default without the recording");
+ Equal("cloud:Kore", VoiceCatalog.Chosen(s, "en", zen, true, clone: false), "and on another service");
+ Check(AIProvider.Ling.Clones && !AIProvider.ZenMux.Clones && !AIProvider.OpenRouter.Clones && !AIProvider.Custom.Clones, "only Ling clones");
+ }
+
+ public static async Task SpeaksInTheOwnVoiceAndFallsBackToWindows()
+ {
+ var old = LingClient.Spacing; LingClient.Spacing = 0;
+ var folder = Path.Combine(Paths.Root, "voice-engine-test");
+ try
+ {
+ var sse = new Service((_, _) => new HttpResponseMessage(HttpStatusCode.OK)
+ {
+ Content = new StringContent("data: {\"audio\":\"AQACAA==\"}\n\ndata: {\"type\":\"speech.audio.done\"}\n\n", System.Text.Encoding.UTF8, "text/event-stream"),
+ });
+ var (ling, s) = Using(sse, "ling");
+ s.SpeakVoices["ja"] = "clone";
+ var reference = new VoiceReference(new PlainProtector(), folder);
+ var voice = new NoVoice();
+ var engine = new SpeakEngine(ling, new Translator(ling), new SessionStore(), s, () => "ja", () => null, voice);
+ // Not recorded: Ming's default voice for Japanese.
+ Check(await engine.Voice("こんにちは", "ja", new Sink()), "spoken");
+ Equal("ming", engine.LastVoice, "Ming's own voice before the recording");
+ engine.Reference = reference;
+ reference.Save(Wav.Bytes(new short[16000 * 11]), "大家好,我是主持人。");
+ Check(engine.CloneReady, "ready with Ling and a recording");
+ Check(await engine.Voice("こんにちは", "ja", new Sink()), "spoken");
+ Equal("clone", engine.LastVoice, "in the user's own voice");
+ var body = JsonNode.Parse(sse.Sent[^1].body)!;
+ Check(body["references"] is JsonArray { Count: 1 } && body["voice"] is null, "the recording went with it");
+ Equal("ja", body["language_id"]!.GetValue<string>(), "with Ming's language");
+ // Ling failing: Windows speaks the translation instead (never the original).
+ var down = new Service((_, _) => new HttpResponseMessage(HttpStatusCode.InternalServerError));
+ var (ling2, s2) = Using(down, "ling");
+ s2.SpeakVoices["ja"] = "clone";
+ var engine2 = new SpeakEngine(ling2, new Translator(ling2), new SessionStore(), s2, () => "ja", () => null, voice) { Reference = reference };
+ Check(await engine2.Voice("こんにちは", "ja", new Sink()), "still spoken");
+ Equal("system", engine2.LastVoice, "by Windows");
+ }
+ finally { LingClient.Spacing = old; try { Directory.Delete(folder, true); } catch { } }
+ }
+
+ public static void TellsASlowRecordingApart()
+ {
+ // 21 characters read over 4 s of sound (a second of silence each side): an ordinary pace.
+ var samples = new float[16000 * 6];
+ for (var i = 16000; i < 16000 * 5; i++) samples[i] = (float)Math.Sin(i * 0.05) * 0.3f;
+ var text = "大家好我是这次会议的主持人今天我们讨论计划";
+ var pace = VoicePace.Pace(text, samples, 16000)!.Value;
+ Check(Math.Abs(pace - 5.25) < 0.1, $"characters over the speech, not the silence ({pace})");
+ Check(!VoicePace.IsSlow(text, pace), "not slow");
+ Check(VoicePace.IsSlow(text, 1.7), "a recital at 1.7 a second is");
+ Check(!VoicePace.IsSlow("hello everyone thanks for joining", 2.0) && VoicePace.IsSlow("hello everyone thanks for joining", 1.5), "words for English");
+ Equal(null, VoicePace.SpeechSpan(new float[16000], 16000), "silence has no span");
+ Equal("hello,it's,大,家", string.Join(",", VoicePace.Tokens("Hello, it’s 大家!")), "tokens as the Mac's");
+ }
+
+ public static async Task ChecksARecordingBeforeKeepingIt()
+ {
+ static byte[] Spoken(double seconds)
+ {
+ var pcm = new short[(int)(16000 * seconds)];
+ for (var i = 8000; i < pcm.Length - 8000; i++) pcm[i] = (short)(Math.Sin(i * 0.05) * 9000);
+ return Wav.Bytes(pcm);
+ }
+ var passage = VoiceCloneCheck.Passage("zh-CN")[..40];
+ Equal(VoiceCloneCheck.Outcome.TooShort, (await VoiceCloneCheck.Check(Spoken(9), _ => Task.FromResult<string?>(passage))).outcome, "under 10 s");
+ Equal(VoiceCloneCheck.Outcome.NotHeard, (await VoiceCloneCheck.Check(Spoken(12), _ => Task.FromResult<string?>("嗯"))).outcome, "nothing recognisable");
+ Equal(VoiceCloneCheck.Outcome.NotHeard, (await VoiceCloneCheck.Check(Spoken(12), _ => throw new LingException(LingException.Kind.Network))).outcome, "the hearing failed");
+ Equal(VoiceCloneCheck.Outcome.Slow, (await VoiceCloneCheck.Check(Spoken(14), _ => Task.FromResult<string?>("大家好我是主持人今天讨论"))).outcome, "12 characters in 13 s");
+ var (ok, text) = await VoiceCloneCheck.Check(Spoken(12), _ => Task.FromResult<string?>(" " + passage + " "));
+ Equal((VoiceCloneCheck.Outcome.Ready, passage), (ok, text), "an ordinary reading is kept with its words");
+ }
+
public static async Task HearingGoesToTheChosenHearModel()
{
Equal(12.0, Translator.HearTimeout(new AppSettings().AIConfig()), "Ming's timeout");