// 文字转语音(TTS 朗读)2.0 // 引擎:WinRT Windows.Media.SpeechSynthesis(Windows 10/11 自带),离线、免费、不联网。 // 相比 1.0(System.Speech/SAPI): // - 语音列表直接含系统全部 OneCore 语音(Kangkang/Yaoyao 等,SAPI 引擎看不到它们), // 无需解锁、无需管理员 // - 语速 SpeakingRate 0.5~2.0 连续可调;音量用 16bit 采样振幅缩放实现 // - 打开/拖入 TXT;长文分段朗读带进度;试听按钮;设置记忆 using System; using System.Collections.Generic; using System.IO; using System.Media; using System.Speech.Synthesis; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.Foundation; using Windows.Media; using Windows.Media.SpeechSynthesis; using Windows.Storage.Streams; /* 双引擎同名类消歧 */ using RtSS = Windows.Media.SpeechSynthesis.SpeechSynthesizer; using SpSS = System.Speech.Synthesis.SpeechSynthesizer; using SpGender = System.Speech.Synthesis.VoiceGender; namespace GtTts { /* ───────────── 异步等待(不引用 System.Runtime.WindowsRuntime 的轮询方案) ───────────── */ internal static class WinRTWait { public static T WaitOp(IAsyncOperation op) where T : class { while (op.Status == AsyncStatus.Started) Thread.Sleep(10); if (op.Status != AsyncStatus.Completed) throw new Exception("WinRT 异步操作失败: " + op.Status); return op.GetResults(); } public static uint WaitU32(IAsyncOperation op) { while (op.Status == AsyncStatus.Started) Thread.Sleep(10); if (op.Status != AsyncStatus.Completed) throw new Exception("WinRT 流读取失败: " + op.Status); return op.GetResults(); } } /* ───────────── 核心:TTS 操作 ───────────── */ public static class TtsOps { public class VoiceItem { public string Name; // 引擎名(SelectVoice 用) public string Display; // 下拉框显示 public string Engine; // "rt"=WinRT / "sapi"=System.Speech } /* 语音表:WinRT(含 OneCore 隐藏语音)∪ SAPI(桌面版语音),按名去重 */ static Dictionary _engineMap; static readonly object _mapLock = new object(); public static string EngineOf(string voiceName) { lock (_mapLock) { if (_engineMap == null) { _engineMap = new Dictionary(); foreach (VoiceItem v in AllVoices()) _engineMap[v.Name] = v.Engine; } string e; return _engineMap.TryGetValue(voiceName ?? "", out e) ? e : "rt"; } } /* 系统全部语音:WinRT ∪ SAPI 去重合并 */ public static List AllVoices() { List list = new List(); { foreach (VoiceInformation v in RtSS.AllVoices) { string disp = v.DisplayName; if (!string.IsNullOrEmpty(v.Language)) disp += " (" + v.Language + ")"; if (v.Gender == Windows.Media.SpeechSynthesis.VoiceGender.Male) disp += " 男声"; else if (v.Gender == Windows.Media.SpeechSynthesis.VoiceGender.Female) disp += " 女声"; list.Add(new VoiceItem { Name = v.DisplayName, Display = disp, Engine = "rt" }); } } try { using (SpSS sp = new SpSS()) { foreach (InstalledVoice v in sp.GetInstalledVoices()) { string name = v.VoiceInfo.Name; bool dup = false; foreach (VoiceItem it in list) if (it.Name == name) { dup = true; break; } if (dup) continue; string disp = name; if (v.VoiceInfo.Culture != null) disp += " (" + v.VoiceInfo.Culture.Name + ")"; if (v.VoiceInfo.Gender == SpGender.Male) disp += " 男声"; else if (v.VoiceInfo.Gender == SpGender.Female) disp += " 女声"; list.Add(new VoiceItem { Name = name, Display = disp, Engine = "sapi" }); } } } catch { /* SAPI 不可用就只用 WinRT */ } return list; } /* 文本 → WAV 字节。rate: -10..10,volume: 0..100。按语音名自动选引擎 */ public static byte[] TextToWavBytes(string text, string voiceName, int rate, int volume) { if (string.IsNullOrWhiteSpace(text)) throw new ArgumentException("文本为空"); if (voiceName != null && EngineOf(voiceName) == "sapi") return SapiToWav(text, voiceName, rate, volume); return RtToWav(text, voiceName, rate, volume); } /* WinRT 引擎合成 */ static byte[] RtToWav(string text, string voiceName, int rate, int volume) { byte[] wav; using (RtSS ss = new RtSS()) { if (!string.IsNullOrEmpty(voiceName)) { foreach (VoiceInformation v in RtSS.AllVoices) if (v.DisplayName == voiceName) { ss.Voice = v; break; } } ss.Options.SpeakingRate = RateToEngine(rate); using (SpeechSynthesisStream st = WinRTWait.WaitOp(ss.SynthesizeTextToStreamAsync(text))) { wav = ReadStreamBytes(st); } } return ScaleVolume(wav, volume); } /* SAPI 引擎合成(桌面版语音,如英文 Zira) */ static byte[] SapiToWav(string text, string voiceName, int rate, int volume) { using (MemoryStream ms = new MemoryStream()) using (SpSS ss = new SpSS()) { try { ss.SelectVoice(voiceName); } catch { } if (rate < -10) rate = -10; if (rate > 10) rate = 10; ss.Rate = rate; ss.Volume = volume < 0 ? 0 : (volume > 100 ? 100 : volume); ss.SetOutputToWaveStream(ms); ss.Speak(text); ss.SetOutputToNull(); return ms.ToArray(); } } /* 语速 -10..10 → 引擎 0.5..2.0,0 → 1.0 */ public static double RateToEngine(int rate) { if (rate < -10) rate = -10; if (rate > 10) rate = 10; return rate >= 0 ? 1.0 + rate * 0.1 : 1.0 + rate * 0.05; } /* SpeechSynthesisStream → byte[](DataReader 走输入流) */ static byte[] ReadStreamBytes(SpeechSynthesisStream st) { ulong size = st.Size; if (size == 0 || size > 512L * 1024 * 1024) throw new Exception("语音流大小异常"); using (DataReader dr = new DataReader(st.GetInputStreamAt(0))) { uint n = WinRTWait.WaitU32(dr.LoadAsync((uint)size)); byte[] b = new byte[n]; dr.ReadBytes(b); return b; } } /* WAV 音量缩放:找 data 块,把 16bit 采样乘 volume/100 */ public static byte[] ScaleVolume(byte[] wav, int volume) { if (volume >= 100 || volume < 0) volume = volume < 0 ? 0 : volume; if (volume == 100 || wav == null || wav.Length < 44) return wav; int dataOff, dataLen; if (!FindDataChunk(wav, out dataOff, out dataLen)) return wav; double k = volume / 100.0; for (int i = dataOff; i + 1 < dataOff + dataLen && i + 1 < wav.Length; i += 2) { short s = (short)(wav[i] | (wav[i + 1] << 8)); int v = (int)Math.Round(s * k); if (v > short.MaxValue) v = short.MaxValue; if (v < short.MinValue) v = short.MinValue; wav[i] = (byte)(v & 0xFF); wav[i + 1] = (byte)((v >> 8) & 0xFF); } return wav; } /* 遍历 RIFF 块找 data 块 */ public static bool FindDataChunk(byte[] wav, out int dataOff, out int dataLen) { dataOff = 0; dataLen = 0; if (wav == null || wav.Length < 12) return false; if (wav[0] != 'R' || wav[1] != 'I' || wav[2] != 'F' || wav[3] != 'F') return false; int pos = 12; while (pos + 8 <= wav.Length) { string id = Encoding.ASCII.GetString(wav, pos, 4); int len = wav[pos + 4] | (wav[pos + 5] << 8) | (wav[pos + 6] << 16) | (unchecked((sbyte)wav[pos + 7]) << 24); if (len < 0 || pos + 8 + (long)len > wav.Length) return false; if (id == "data") { dataOff = pos + 8; dataLen = len; return true; } pos += 8 + len; if (len % 2 == 1) pos++; // 块按 2 字节对齐 } return false; } /* 文本 → WAV 文件 */ public static string TextToWavFile(string text, string outPath, string voiceName, int rate, int volume) { byte[] wav = TextToWavBytes(text, voiceName, rate, volume); File.WriteAllBytes(outPath, wav); return outPath; } /* WAV 最大振幅(抽稀),测试用 */ public static int MaxAbsSample(byte[] wav) { int off, len; if (!FindDataChunk(wav, out off, out len)) return 0; int max = 0; for (int i = off; i + 1 < off + len && i + 1 < wav.Length; i += 2) { short s = (short)(wav[i] | (wav[i + 1] << 8)); int a = Math.Abs(s); if (a > max) max = a; if (i - off > 400000) break; } return max; } /* 长文本分段(按句子断开,每段不超 maxChars) */ public static List SplitText(string text, int maxChars) { List parts = new List(); if (string.IsNullOrWhiteSpace(text)) return parts; if (maxChars < 20) maxChars = 20; string cur = ""; foreach (char c in text) { cur += c; if (cur.Length >= maxChars && "。!?;\n.!?\r".IndexOf(c) >= 0) { parts.Add(cur.Trim()); cur = ""; } } if (cur.Trim().Length > 0) parts.Add(cur.Trim()); return parts; } /* 估算时长(按中文 3.5 字/秒、英文 11 字符/秒的粗略值,rate 修正) */ public static double EstimateSeconds(string text, int rate) { if (string.IsNullOrEmpty(text)) return 0; int cjk = 0, other = 0; foreach (char c in text) { if (c >= 0x4E00 && c <= 0x9FFF) cjk++; else if (!char.IsWhiteSpace(c)) other++; } double secs = cjk / 3.5 + other / 11.0; double factor = 1.0 / RateToEngine(rate); return Math.Round(secs * factor, 1); } /* WAV 头是否合法(RIFF....WAVE) */ public static bool IsValidWav(byte[] b) { return b != null && b.Length > 44 && b[0] == 'R' && b[1] == 'I' && b[2] == 'F' && b[3] == 'F' && b[8] == 'W' && b[9] == 'A' && b[10] == 'V' && b[11] == 'E'; } /* ─────── 设置记忆 ─────── */ public static string SettingsPath() { string dir = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "GreenToolBox"); try { Directory.CreateDirectory(dir); } catch { } return Path.Combine(dir, "tts.ini"); } public static void SaveSettings(string voice, int rate, int volume) { try { File.WriteAllLines(SettingsPath(), new string[] { "voice=" + (voice ?? ""), "rate=" + rate, "volume=" + volume }); } catch { } } public static Dictionary LoadSettings() { Dictionary d = new Dictionary(); try { foreach (string line in File.ReadAllLines(SettingsPath())) { int i = line.IndexOf('='); if (i > 0) d[line.Substring(0, i)] = line.Substring(i + 1); } } catch { } return d; } } /* ───────────── 界面(2.0) ───────────── */ public class TtsForm : Form { public bool headless; TextBox _text; ComboBox _voice; TrackBar _rate, _volume; Button _play, _stop, _export, _open, _preview; Label _status, _prog; SoundPlayer _sp; volatile bool _playing; List _chunks = new List(); int _chunkIdx; public TtsForm() { Text = "文字转语音 — 绿色工具箱"; Font = new System.Drawing.Font("Microsoft YaHei UI", 9F); Size = new System.Drawing.Size(640, 600); StartPosition = FormStartPosition.CenterScreen; FormBorderStyle = FormBorderStyle.FixedSingle; MaximizeBox = false; AllowDrop = true; Controls.Add(MakeLabel("要朗读的文字(可粘贴长文,也可拖入 TXT 文件):", 12, 12, 340)); _text = new TextBox(); _text.Multiline = true; _text.ScrollBars = ScrollBars.Vertical; _text.SetBounds(12, 36, 600, 280); _text.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom; Controls.Add(_text); int y = 330; Controls.Add(MakeLabel("语音", 12, y + 4, 40)); _voice = new ComboBox(); _voice.DropDownStyle = ComboBoxStyle.DropDownList; _voice.SetBounds(56, y, 400, 24); Controls.Add(_voice); _open = MakeButton("打开文件…", 500, y - 1, 100); _open.Click += delegate { OpenFile(); }; Controls.Add(_open); y += 36; Controls.Add(MakeLabel("语速", 12, y + 4, 40)); _rate = new TrackBar(); _rate.Minimum = -10; _rate.Maximum = 10; _rate.Value = 0; _rate.TickStyle = TickStyle.None; _rate.SetBounds(56, y - 6, 200, 30); Controls.Add(_rate); Controls.Add(MakeLabel("音量", 280, y + 4, 40)); _volume = new TrackBar(); _volume.Minimum = 0; _volume.Maximum = 100; _volume.Value = 100; _volume.TickStyle = TickStyle.None; _volume.SetBounds(324, y - 6, 200, 30); Controls.Add(_volume); y += 40; _play = MakeButton("朗读", 12, y, 90); _play.Click += delegate { Play(); }; Controls.Add(_play); _stop = MakeButton("停止", 114, y, 90); _stop.Enabled = false; _stop.Click += delegate { StopAll(); }; Controls.Add(_stop); _export = MakeButton("导出 WAV", 216, y, 100); _export.Click += delegate { Export(); }; Controls.Add(_export); _preview = MakeButton("试听声音", 326, y, 100); _preview.Click += delegate { PreviewVoice(); }; Controls.Add(_preview); y += 40; _prog = MakeLabel("", 12, y, 600); _prog.ForeColor = System.Drawing.Color.FromArgb(0, 110, 60); Controls.Add(_prog); y += 26; _status = MakeLabel("离线朗读,文字不出电脑。语音列表含系统全部隐藏语音。", 12, y, 600); _status.ForeColor = System.Drawing.Color.FromArgb(0, 110, 60); Controls.Add(_status); _sp = new SoundPlayer(); RefreshVoices(null); LoadPrefs(); DragEnter += delegate (object s, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; DragDrop += delegate (object s, DragEventArgs e) { string[] paths = (string[])e.Data.GetData(DataFormats.FileDrop); if (paths != null && paths.Length > 0) LoadTextFile(paths[0]); }; } void RefreshVoices(string prefer) { _voice.Items.Clear(); foreach (TtsOps.VoiceItem v in TtsOps.AllVoices()) _voice.Items.Add(v.Display); if (_voice.Items.Count == 0) return; int pick = 0; if (prefer != null) for (int i = 0; i < _voice.Items.Count; i++) if (_voice.Items[i].ToString().StartsWith(prefer)) { pick = i; break; } _voice.SelectedIndex = pick; } void LoadPrefs() { Dictionary p = TtsOps.LoadSettings(); string v; if (p.TryGetValue("voice", out v) && v.Length > 0) for (int i = 0; i < _voice.Items.Count; i++) if (_voice.Items[i].ToString().StartsWith(v)) { _voice.SelectedIndex = i; break; } int n; if (p.TryGetValue("rate", out v) && int.TryParse(v, out n)) _rate.Value = Math.Max(_rate.Minimum, Math.Min(_rate.Maximum, n)); if (p.TryGetValue("volume", out v) && int.TryParse(v, out n)) _volume.Value = Math.Max(_volume.Minimum, Math.Min(_volume.Maximum, n)); } void OpenFile() { using (OpenFileDialog od = new OpenFileDialog()) { od.Filter = "文本文件|*.txt;*.md;*.csv;*.log;*.ini|所有文件|*.*"; if (od.ShowDialog(this) == DialogResult.OK) LoadTextFile(od.FileName); } } void LoadTextFile(string path) { try { _text.Text = File.ReadAllText(path); _status.Text = "已载入:" + Path.GetFileName(path) + "(" + _text.Text.Length + " 字)"; } catch (Exception ex) { _status.Text = "读不了这个文件:" + ex.Message; } } Label MakeLabel(string text, int x, int y, int w) { Label l = new Label(); l.Text = text; l.SetBounds(x, y, w, 22); l.AutoSize = false; return l; } Button MakeButton(string text, int x, int y, int w) { Button b = new Button(); b.Text = text; b.SetBounds(x, y, w, 30); return b; } string SelectedVoice() { if (_voice.SelectedIndex < 0) return null; string desc = _voice.SelectedItem.ToString(); int i = desc.IndexOf(" ("); return i > 0 ? desc.Substring(0, i) : desc; } /* 后台线程:逐段 PlaySync 接力,段间响应取消 */ void PlayChunks(List chunks) { _chunks = chunks; _chunkIdx = 0; _playing = true; _play.Enabled = false; _stop.Enabled = true; UpdateProg(); ThreadPool.QueueUserWorkItem(delegate { for (int i = 0; i < _chunks.Count; i++) { if (!_playing) break; _chunkIdx = i; try { SafeInvoke(delegate { UpdateProg(); }); } catch { } try { byte[] wav = TtsOps.TextToWavBytes(_chunks[i], SelectedVoice(), _rate.Value, _volume.Value); using (MemoryStream ms = new MemoryStream(wav)) { _sp.Stream = ms; _sp.PlaySync(); } } catch (Exception ex) { SafeInvoke(delegate { _status.Text = "朗读失败:" + ex.Message; }); break; } } bool finished = _playing; _playing = false; SafeInvoke(delegate { _play.Enabled = true; _stop.Enabled = false; if (finished) { _prog.Text = ""; _status.Text = "朗读完成"; } }); }); } void UpdateProg() { _prog.Text = _chunks.Count > 1 ? "第 " + (_chunkIdx + 1) + " / 共 " + _chunks.Count + " 段 (停止在段与段之间生效)" : ""; } void SafeInvoke(MethodInvoker m) { try { BeginInvoke(m); } catch { } } void Play() { if (_playing) return; string text = _text.Text.Trim(); if (text.Length == 0) { _status.Text = "请先输入文字"; return; } _status.Text = "正在朗读…"; List chunks = text.Length > 150 ? TtsOps.SplitText(text, 150) : new List(new string[] { text }); PlayChunks(chunks); } void PreviewVoice() { StopAll(); _status.Text = "试听中:" + SelectedVoice(); PlayChunks(new List(new string[] { "你好,我是" + (SelectedVoice() ?? "默认") + ",很高兴为你朗读。" })); } void StopAll() { _playing = false; try { _sp.Stop(); } catch { } _play.Enabled = true; _stop.Enabled = false; _prog.Text = ""; } void Export() { string text = _text.Text.Trim(); if (text.Length == 0) { _status.Text = "请先输入文字"; return; } using (SaveFileDialog sd = new SaveFileDialog()) { sd.Filter = "WAV 音频|*.wav"; sd.FileName = "朗读_" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".wav"; if (sd.ShowDialog(this) == DialogResult.OK) { try { TtsOps.TextToWavFile(text, sd.FileName, SelectedVoice(), _rate.Value, _volume.Value); _status.Text = "已导出:" + Path.GetFileName(sd.FileName); try { System.Diagnostics.Process.Start("explorer.exe", "/select,\"" + sd.FileName + "\""); } catch { } } catch (Exception ex) { _status.Text = "导出失败:" + ex.Message; } } } } protected override void OnFormClosed(FormClosedEventArgs e) { TtsOps.SaveSettings(SelectedVoice(), _rate.Value, _volume.Value); StopAll(); _sp.Dispose(); base.OnFormClosed(e); } protected override void SetVisibleCore(bool value) { base.SetVisibleCore(headless ? false : value); } } /* ───────────── 自测 ───────────── */ public static class TtsSelfTest { static int _pass, _fail; static List _lines = new List(); static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } static void CheckTrue(string name, bool cond) { Check(name, cond, true); } public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("文字转语音 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); string baseDir = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-tts-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); try { Console.OutputEncoding = Encoding.UTF8; } catch { } // 0. 语音可用性(WinRT 引擎,应比 SAPI 多) List voices = TtsOps.AllVoices(); CheckTrue("WinRT 引擎有语音", voices.Count > 0); _lines.Add(" (语音 " + voices.Count + " 个:" + string.Join("、", voices.ConvertAll(delegate (TtsOps.VoiceItem v) { return v.Name; }).ToArray()) + ")"); // 1. 中文合成 WAV string zhPath = Path.Combine(baseDir, "zh.wav"); TtsOps.TextToWavFile("绿色工具箱文字转语音测试", zhPath, null, 0, 100); byte[] zh = File.ReadAllBytes(zhPath); CheckTrue("中文 WAV 魔数", TtsOps.IsValidWav(zh)); CheckTrue("中文 WAV 有数据(>20KB)", zh.Length > 20 * 1024); int off, len; CheckTrue("data 块定位", TtsOps.FindDataChunk(zh, out off, out len) && len > 1000); // 2. 英文合成 string enPath = Path.Combine(baseDir, "en.wav"); TtsOps.TextToWavFile("Hello TTS test one two three", enPath, null, 0, 100); CheckTrue("英文 WAV 魔数", TtsOps.IsValidWav(File.ReadAllBytes(enPath))); // 3. 语速差异:快语速文件应更小 string fastPath = Path.Combine(baseDir, "fast.wav"); TtsOps.TextToWavFile("这是一段用来测试语速差异的文本内容", fastPath, null, 10, 100); string slowPath = Path.Combine(baseDir, "slow.wav"); TtsOps.TextToWavFile("这是一段用来测试语速差异的文本内容", slowPath, null, -10, 100); CheckTrue("快语速文件更小", new FileInfo(fastPath).Length < new FileInfo(slowPath).Length); // 4. 音量缩放:50 音量最大振幅应明显小于 100 byte[] full = TtsOps.TextToWavBytes("音量缩放测试文本", null, 0, 100); byte[] half = TtsOps.TextToWavBytes("音量缩放测试文本", null, 0, 50); int mFull = TtsOps.MaxAbsSample(full), mHalf = TtsOps.MaxAbsSample(half); CheckTrue("半音量振幅更小", mHalf < mFull); CheckTrue("半音量振幅约为一半(±20%)", Math.Abs(mHalf - mFull / 2.0) < mFull * 0.2); // 5. 指定语音合成(逐个不抛异常) foreach (TtsOps.VoiceItem v in voices) { string p = Path.Combine(baseDir, "v_" + v.Name.GetHashCode().ToString("x") + ".wav"); TtsOps.TextToWavFile("指定语音测试", p, v.Name, 0, 100); if (!TtsOps.IsValidWav(File.ReadAllBytes(p))) CheckTrue("语音 " + v.Name + " 合成", false); } CheckTrue("全部语音合成成功", true); // 6. 长文本分段 StringBuilder sb = new StringBuilder(); for (int i = 0; i < 30; i++) sb.Append("这是第").Append(i + 1).Append("句测试文本,用于验证分段逻辑。"); List parts = TtsOps.SplitText(sb.ToString(), 50); CheckTrue("长文分段多段", parts.Count >= 5); bool allFit = true; foreach (string p in parts) if (p.Length > 60) allFit = false; CheckTrue("分段长度受控", allFit); // 7. 空文本分段与时长估算 Check("空文本分段", TtsOps.SplitText("", 50).Count, 0); CheckTrue("时长估算为正", TtsOps.EstimateSeconds("一二三四五", 0) > 0); CheckTrue("快语速估算更短", TtsOps.EstimateSeconds("一二三四五六七八十", 5) < TtsOps.EstimateSeconds("一二三四五六七八十", -5)); Check("语速映射 0", TtsOps.RateToEngine(0), 1.0); CheckTrue("语速映射范围", TtsOps.RateToEngine(10) == 2.0 && TtsOps.RateToEngine(-10) == 0.5); // 8. 异常输入 try { TtsOps.TextToWavBytes(" ", null, 0, 100); Check("空文本抛异常", false, true); } catch (ArgumentException) { Check("空文本抛异常", true, true); } // 9. 设置记忆读写回环 TtsOps.SaveSettings("TestVoice", 3, 80); Dictionary rp = TtsOps.LoadSettings(); string vv; CheckTrue("设置保存加载", rp.TryGetValue("voice", out vv) && vv == "TestVoice"); CheckTrue("语速保存加载", rp.ContainsKey("rate") && rp["rate"] == "3"); // 10. Form 层 TtsForm form = new TtsForm(); form.headless = true; CheckTrue("窗体控件就绪", form.Controls.Count >= 10); } catch (Exception ex) { _lines.Add("异常: " + ex.GetType().Name + ": " + ex.Message + ex.StackTrace); _fail++; } _lines.Add("结果: " + _pass + " 通过, " + _fail + " 失败"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-tts.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } /* ───────────── 入口 ───────────── */ static class Program { [STAThread] static int Main(string[] args) { if (args.Length >= 1 && args[0] == "--selftest") return TtsSelfTest.Run(args.Length >= 2 ? args[1] : null); if (args.Length >= 2 && args[0] == "--speak") { try { byte[] wav = TtsOps.TextToWavBytes(args[1], null, 0, 100); using (MemoryStream ms = new MemoryStream(wav)) using (SoundPlayer sp = new SoundPlayer(ms)) { sp.PlaySync(); } return 0; } catch { return 1; } } using (Mutex mutex = new Mutex(true, "GT-TTS-单实例")) { if (!mutex.WaitOne(0, false)) return 0; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TtsForm()); } return 0; } } }