dsh-watch-together 0.3.4 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,6 +14,7 @@ main{max-width:900px;margin:0 auto;padding:32px 20px 64px}h1{font-size:24px;marg
14
14
  .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:12px}
15
15
  label.field{display:flex;flex-direction:column;gap:6px;font-weight:600;font-size:13px}
16
16
  input[type=text],input[type=password],input[type=number],select{width:100%;padding:9px 10px;border:1px solid var(--line);border-radius:8px;background:var(--bg);color:var(--text);font:inherit}
17
+ input[type=range]{width:100%;margin:8px 0}
17
18
  input[type=checkbox]{margin-right:8px}.check{display:flex;align-items:center;font-weight:500;color:var(--text)}
18
19
  .hint{font-size:12px;color:var(--muted);font-weight:400}.actions{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:16px}
19
20
  button{padding:9px 14px;border:1px solid var(--line);border-radius:8px;background:var(--card);color:var(--text);font:inherit;cursor:pointer}
@@ -58,6 +59,49 @@ code{font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;background:var
58
59
  <input id="adapter" type="text" placeholder="D:/code/my-voice.mjs 或包名;留空关闭">
59
60
  <span class="hint">核心只负责 import 和转发,不自带 TTS。示例见 examples/voice-edge-tts。</span>
60
61
  </label>
62
+ <label class="field">引擎
63
+ <select id="ttsEngine">
64
+ <option value="">自动 —— 默认本地 SAPI;配了 edgeTts 路径/环境变量才走云端</option>
65
+ <option value="sapi">本地 SAPI —— 文本不出机器(系统嗓)</option>
66
+ <option value="edge">微软 Edge —— 神经音色(文本会发给微软)</option>
67
+ </select>
68
+ <span class="hint">选 Edge = 要念的文本离开这台机器;不介意再选。</span>
69
+ </label>
70
+ <label class="field">人声选择
71
+ <select id="ttsVoice">
72
+ <option value="zh-CN-XiaoxiaoNeural">中文-普通-女声 晓晓</option>
73
+ <option value="zh-CN-XiaoxuanNeural">中文-普通-女声 晓萱</option>
74
+ <option value="zh-CN-XiaoyiNeural">中文-普通-女声 晓伊</option>
75
+ <option value="zh-CN-YunxiNeural">中文-普通-男声 云希</option>
76
+ <option value="zh-CN-YunjianNeural">中文-普通-男声 云健</option>
77
+ <option value="zh-CN-YunyangNeural">中文-多风格-男声 云扬</option>
78
+ <option value="zh-CN-YunxiaNeural">中文-普通-男声 云夏</option>
79
+ <option value="zh-CN-YunzeNeural">中文-普通-男声 云泽</option>
80
+ <option value="zh-CN-liaoning-XiaobeiNeural">中文-辽宁-女声 晓北</option>
81
+ <option value="zh-CN-shaanxi-XiaoniNeural">中文-陕西-女声 晓妮</option>
82
+ </select>
83
+ <span class="hint">Edge 引擎的神经音色;本地 SAPI 只有系统嗓,选了不生效。</span>
84
+ </label>
85
+ <label class="field">朗读速度
86
+ <input id="ttsRate" type="range" min="-10" max="10" step="0.5">
87
+ <span class="hint" id="rateHint">-10 ~ +10。</span>
88
+ </label>
89
+ <label class="field">朗读声调
90
+ <input id="ttsPitch" type="range" min="-20" max="20" step="1">
91
+ <span class="hint" id="pitchHint">负数更低沉、正数更清亮。</span>
92
+ </label>
93
+ <label class="field">朗读音量
94
+ <input id="ttsVolume" type="range" min="0" max="100" step="5">
95
+ <span class="hint" id="volumeHint">100 = 不增不减。</span>
96
+ </label>
97
+ <label class="field">试听文本
98
+ <input id="ttsTestText" type="text" placeholder="这是一句试听文本,听起来怎么样?">
99
+ <span class="hint">按面板当前参数念一句;试听不保存设置。</span>
100
+ </label>
101
+ <label class="field">试听
102
+ <button class="primary" id="ttsTest">试听</button>
103
+ <span class="hint" id="ttsTestStatus">点一下出声;结果会写明实际用的引擎。</span>
104
+ </label>
61
105
  </div>
62
106
  <div class="banner" id="voiceHint">留空 = 台词只写进聊天记录,不念出来。</div>
63
107
  </div>
@@ -142,11 +186,12 @@ code{font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;background:var
142
186
  const token = new URLSearchParams(location.search).get('token') || '';
143
187
  const apiBase = '/dsh-watch-together/settings/api';
144
188
  const $ = (id) => document.getElementById(id);
145
- const state = { video: null, watch: null, voice: null, window: null, checks: [], paths: {} };
189
+ const state = { video: null, watch: null, voice: null, tts: null, window: null, checks: [], paths: {} };
146
190
 
147
- async function api(path, body) {
191
+ async function api(path, body, signal) {
148
192
  const res = await fetch(apiBase + path, {
149
193
  method: body ? 'POST' : 'GET',
194
+ signal: signal || undefined,
150
195
  headers: { 'x-settings-token': token, 'content-type': 'application/json' },
151
196
  body: body ? JSON.stringify(body) : undefined,
152
197
  });
@@ -165,14 +210,40 @@ code{font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;background:var
165
210
  return String(value || '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
166
211
  }
167
212
 
213
+ // 面板当前的 tts 值:保存和试听共用同一份换算
214
+ function ttsPayload() {
215
+ const pitch = $('ttsPitch').value;
216
+ return {
217
+ engine: $('ttsEngine').value,
218
+ voice: $('ttsVoice').value,
219
+ rate: Number($('ttsRate').value) || 0,
220
+ pitch: pitch && Number(pitch) !== 0 ? (Number(pitch) > 0 ? '+' + Number(pitch) : pitch) : '',
221
+ volume: Number($('ttsVolume').value),
222
+ };
223
+ }
224
+
225
+ function renderTtsHints() {
226
+ const rate = Number($('ttsRate').value) || 0;
227
+ $('rateHint').textContent = '当前 ' + rate + ' 档(约 ' + Math.round(rate * 3) + '%);-10 ~ +10。';
228
+ const pitch = Number($('ttsPitch').value) || 0;
229
+ $('pitchHint').textContent = '当前 ' + (pitch > 0 ? '+' : '') + pitch + 'Hz;负数更低沉、正数更清亮。';
230
+ $('volumeHint').textContent = '当前 ' + $('ttsVolume').value + ';100 = 不增不减。';
231
+ }
232
+
168
233
  function render() {
169
234
  const v = state.video || {};
170
235
  const w = state.watch || {};
171
236
  const s = state.voice || {};
237
+ const t = state.tts || {};
172
238
  const win = state.window || {};
173
239
  $('browserPort').value = v.browserPort || '';
174
240
  $('chatPort').value = w.chatPort || '';
175
241
  $('adapter').value = s.adapter || '';
242
+ $('ttsEngine').value = typeof t.engine === 'string' ? t.engine : '';
243
+ $('ttsVoice').value = (typeof t.voice === 'string' && t.voice) ? t.voice : 'zh-CN-XiaoxiaoNeural';
244
+ $('ttsRate').value = t.rate === undefined ? 0 : t.rate;
245
+ $('ttsPitch').value = String(t.pitch === undefined || t.pitch === '' ? 0 : t.pitch).replace(/[^\d+-]/g, '');
246
+ $('ttsVolume').value = t.volume === undefined ? 100 : t.volume;
176
247
  $('windowStyle').value = win.style || 'auto';
177
248
  $('windowMode').value = win.mode || 'full';
178
249
  $('windowDanmaku').value = win.danmaku ? 'on' : 'off';
@@ -189,9 +260,11 @@ code{font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;background:var
189
260
  : win.style === 'live'
190
261
  ? '当前:实时玻璃 —— 每帧抓屏 + 模糊。觉得卡就换成「静态磨砂」。'
191
262
  : '当前:自动 —— 远程/录屏环境用纯色,其余用实时玻璃;觉得卡可以手动选「静态磨砂」。';
263
+ renderTtsHints();
192
264
  $('paths').innerHTML = '<div>video.json:<code>' + escapeHtml(state.paths.video || '') + '</code></div>'
193
265
  + '<div>watch.json:<code>' + escapeHtml(state.paths.watch || '') + '</code></div>'
194
266
  + '<div>voice.json:<code>' + escapeHtml(state.paths.voice || '') + '</code></div>'
267
+ + '<div>tts.json:<code>' + escapeHtml(state.paths.tts || '') + '</code></div>'
195
268
  + '<div>watch-window.json:<code>' + escapeHtml(state.paths.window || '') + '</code></div>';
196
269
  }
197
270
 
@@ -234,6 +307,7 @@ code{font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;background:var
234
307
  try {
235
308
  const data = await api('/state');
236
309
  state.video = data.video; state.watch = data.watch; state.voice = data.voice;
310
+ state.tts = data.tts;
237
311
  state.window = data.window;
238
312
  state.checks = data.checks || []; state.paths = data.paths || {};
239
313
  render(); renderChecks();
@@ -250,16 +324,18 @@ code{font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;background:var
250
324
  };
251
325
  const watch = { chatPort: Number($('chatPort').value) };
252
326
  const voice = { adapter: $('adapter').value };
327
+ const tts = ttsPayload();
253
328
  const win = {
254
329
  style: $('windowStyle').value,
255
330
  mode: $('windowMode').value,
256
331
  danmaku: $('windowDanmaku').value === 'on',
257
332
  };
258
- const data = await api('/save', { video, watch, voice, window: win });
333
+ const data = await api('/save', { video, watch, voice, tts, window: win });
259
334
  state.video = data.video; state.watch = data.watch; state.voice = data.voice;
335
+ state.tts = data.tts;
260
336
  state.window = data.window;
261
337
  render();
262
- setStatus('已保存;悬浮窗样式立刻生效,语音下一场生效,聊天端口若服务已在跑需重启 DSH。', 'ok');
338
+ setStatus('已保存;悬浮窗样式立刻生效,声音参数下一场生效,语音下一场生效,聊天端口若服务已在跑需重启 DSH。', 'ok');
263
339
  } catch (e) { setStatus(e.message, 'bad'); }
264
340
  }
265
341
 
@@ -273,8 +349,39 @@ code{font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;background:var
273
349
  } catch (e) { setStatus(e.message, 'bad'); }
274
350
  }
275
351
 
352
+ // 试听:按面板当前参数念一句(不落盘)。**新顶旧** —— 上一次还在跑就掐掉重来,
353
+ // 按钮永不吞点击(跑着的时候静默空转,用户看到的就是「点了没反应」)。
354
+ let testAbort = null;
355
+ async function ttsTest() {
356
+ if (testAbort) { try { testAbort.abort(); } catch { /* 已经结束 */ } }
357
+ const controller = new AbortController();
358
+ testAbort = controller;
359
+ const btn = $('ttsTest');
360
+ btn.textContent = '试听中…(点击重试)';
361
+ $('ttsTestStatus').textContent = '试听中…(合成器常驻时约半秒出声)';
362
+ try {
363
+ const r = await api('/tts-test', { text: $('ttsTestText').value, tts: ttsPayload() }, controller.signal);
364
+ const engine = {
365
+ 'edge-stream': '微软神经音(常驻通道)', 'edge-tts': '微软神经音(逐句兜底)', sapi: '本地系统嗓(SAPI)',
366
+ }[r.engine] || r.engine;
367
+ $('ttsTestStatus').textContent = r.ok
368
+ ? '已试听:' + engine + '(首声 ' + (r.firstMs ?? r.ms ?? '?') + 'ms)。'
369
+ : '试听失败:' + (r.reason || '未知原因');
370
+ } catch (e) {
371
+ $('ttsTestStatus').textContent = '试听失败:' + e.message;
372
+ } finally {
373
+ btn.textContent = '试听';
374
+ testAbort = null;
375
+ }
376
+ }
377
+
276
378
  $('save').addEventListener('click', save);
277
379
  $('check').addEventListener('click', check);
380
+ $('ttsTest').addEventListener('click', ttsTest);
381
+ // 滑块拖动实时刷新说明文字(真正落盘还是点保存)
382
+ for (const id of ['ttsRate', 'ttsPitch', 'ttsVolume']) {
383
+ $(id).addEventListener('input', renderTtsHints);
384
+ }
278
385
  // 下拉一改就把说明也换掉(真正落盘还是点保存;这里只是别让提示和选中的对不上)
279
386
  $('windowStyle').addEventListener('change', () => {
280
387
  state.window = { ...(state.window || {}), style: $('windowStyle').value };
@@ -291,4 +398,4 @@ code{font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;background:var
291
398
  load();
292
399
  })();
293
400
  </script>
294
- </body></html>
401
+ </body></html>
@@ -7,12 +7,13 @@
7
7
 
8
8
  import { checkEnvironment } from './deps.js';
9
9
  import {
10
- configPaths, readVideoSettings, readVoiceSettings, readWatchSettings,
11
- readWindowSettings, writeVideoSettings, writeVoiceSettings, writeWatchSettings,
10
+ configPaths, readTtsSettings, readVideoSettings, readVoiceSettings, readWatchSettings,
11
+ readWindowSettings, writeTtsSettings, writeVideoSettings, writeVoiceSettings, writeWatchSettings,
12
12
  writeWindowSettings,
13
13
  } from './config.js';
14
14
  import { settingsPage } from './page.js';
15
15
  import { settingsToken } from './token.js';
16
+ import { runTtsTest, stopTtsTestStream } from './tts-test.js';
16
17
 
17
18
  const PAGE_PATH = '/dsh-watch-together/settings';
18
19
  const API_PREFIX = PAGE_PATH + '/api';
@@ -63,6 +64,7 @@ function statePayload(env) {
63
64
  video: readVideoSettings(env),
64
65
  watch: readWatchSettings(env),
65
66
  voice: readVoiceSettings(env),
67
+ tts: readTtsSettings(env),
66
68
  window: readWindowSettings(env),
67
69
  paths: configPaths(env),
68
70
  };
@@ -105,6 +107,8 @@ export function createSettingsPage({ ctx, env = process.env, log = () => {} } =
105
107
  if (body.video !== undefined) writeVideoSettings(body.video, env);
106
108
  if (body.watch !== undefined) writeWatchSettings(body.watch, env);
107
109
  if (body.voice !== undefined) writeVoiceSettings(body.voice, env);
110
+ // 声音调节:写 tts.json(音色/语速/语调/音量),下一场陪看时读取
111
+ if (body.tts !== undefined) writeTtsSettings(body.tts, env);
108
112
  // 悬浮窗样式:写 watch-window.json,窗口下一拍(250ms)自己换过来
109
113
  if (body.window !== undefined) writeWindowSettings(body.window, env);
110
114
  return json(res, 200, statePayload(env));
@@ -112,6 +116,12 @@ export function createSettingsPage({ ctx, env = process.env, log = () => {} } =
112
116
  if (req.method === 'POST' && action === '/check') {
113
117
  return json(res, 200, { checks: await checkEnvironment(ctx, env) });
114
118
  }
119
+ // 试听:按请求里的面板当前参数念一句(不落盘),回实际出声的引擎和首声耗时
120
+ if (req.method === 'POST' && action === '/tts-test') {
121
+ const body = await readBody(req);
122
+ if (!body || typeof body !== 'object') throw new Error('请求体必须是对象');
123
+ return json(res, 200, await runTtsTest({ text: body.text, tts: body.tts, env }));
124
+ }
115
125
  return json(res, 404, { error: 'not found' });
116
126
  } catch (e) {
117
127
  const message = String(e?.message ?? e).slice(0, 300);
@@ -193,6 +203,7 @@ export function createSettingsPage({ ctx, env = process.env, log = () => {} } =
193
203
  dispose() {
194
204
  if (disposed) return;
195
205
  disposed = true;
206
+ try { stopTtsTestStream(); } catch { /* ignore */ }
196
207
  try { offIndex?.(); } catch { /* ignore */ }
197
208
  try { routeDispose?.(); } catch { /* ignore */ }
198
209
  },
@@ -0,0 +1,243 @@
1
+ /**
2
+ * settings/tts-test.js — 「试听」:按面板当前参数真的念一句(ACT.TTS_CN 的"测试"同款)。
3
+ *
4
+ * 走的是**陪看同一条合成链**,优先级和 `examples/voice-edge-tts/index.mjs` 一致:
5
+ * 常驻合成器(stream/daemon.py)→ edge-tts 逐句兜底 → SAPI 系统嗓。
6
+ * 哪一环真的出了声就报哪一环;显式选了 Edge 就不静默退回系统嗓,直接报失败原因 ——
7
+ * 试听要如实,不是"怎么都能响"。
8
+ *
9
+ * 两件让试听"跟手"的事(2026-11-21 用户报「延迟有点高、有时候点了没反应」):
10
+ * 1. **常驻热合成器**:所有试听共用一个 daemon,参数随请求带(滑块随便拉不重启),
11
+ * 第二次起首声 ~几百毫秒,不再每次冷启动 python + 建连;
12
+ * 2. **新顶旧**:跑着的试听被下一次立刻掐断(AbortSignal + 通道 interrupt),
13
+ * 回执 `reason:'interrupted'` —— 和陪看发声同一个原则:新的直接顶掉旧的。
14
+ *
15
+ * 注意:这里 import 了 `examples/voice-edge-tts/stream/client.mjs`(daemon 的 JSON 行
16
+ * 协议包装)。这不是"核心依赖示例适配器"——核心仍然只发事件(src/voice.js);
17
+ * 是设置页的试听**故意**复用官方示例的常驻通道,保证"试听听到的"和"陪看听到的"同链。
18
+ */
19
+
20
+ import { existsSync } from 'node:fs';
21
+ import { fileURLToPath } from 'node:url';
22
+
23
+ import { defaultEdgeTtsBin, speak, speakViaEdgeTts, ttsPolicy } from '../../bin/tts.mjs';
24
+ import { pythonFor, startStream } from '../../examples/voice-edge-tts/stream/client.mjs';
25
+ import { effectiveTtsSettings } from './config.js';
26
+
27
+ export const TTS_TEST_DEFAULT_TEXT = '这是一句试听文本,听起来怎么样?';
28
+ export const TTS_TEST_MAX_TEXT = 200;
29
+
30
+ const DAEMON = fileURLToPath(new URL('../../examples/voice-edge-tts/stream/daemon.py', import.meta.url));
31
+
32
+ /* ------------------------------------------------- 常驻热合成器(试听共用) */
33
+
34
+ let warmStream = null;
35
+ let warmStarts = 0;
36
+ let idleTimer = null;
37
+ let currentRun = null; // 在飞的那一次试听(新顶旧用)
38
+ const IDLE_STOP_MS = 3 * 60_000;
39
+
40
+ /** 试听次数相关的可观测量(回归测试守"复用,不冷启动"用)。 */
41
+ export function ttsTestStreamStats() {
42
+ return { starts: warmStarts, warm: !!(warmStream && warmStream.alive) };
43
+ }
44
+
45
+ /** 停掉常驻合成器(设置 API 卸载 / 闲置 / 测试收尾用)。 */
46
+ export function stopTtsTestStream() {
47
+ clearTimeout(idleTimer);
48
+ idleTimer = null;
49
+ const stream = warmStream;
50
+ warmStream = null;
51
+ if (stream) {
52
+ try { stream.stop(); } catch { /* 已经退了 */ }
53
+ }
54
+ }
55
+
56
+ function touchIdle() {
57
+ clearTimeout(idleTimer);
58
+ idleTimer = setTimeout(() => { stopTtsTestStream(); }, IDLE_STOP_MS);
59
+ if (typeof idleTimer.unref === 'function') idleTimer.unref(); // 别把宿主进程吊住
60
+ }
61
+
62
+ /**
63
+ * 拿(或起)常驻合成器:同一个进程里所有试听共用一个。
64
+ * `start` 是测试接缝(默认真起 daemon.py);起不来返回 null,调用方退回逐句链。
65
+ */
66
+ export function acquireTtsTestStream(env = process.env, start = startStream) {
67
+ if (warmStream && warmStream.alive) {
68
+ touchIdle();
69
+ return warmStream;
70
+ }
71
+ stopTtsTestStream();
72
+ const bin = defaultEdgeTtsBin(env);
73
+ const python = bin ? pythonFor(bin) : null;
74
+ if (!python || !existsSync(DAEMON)) return null;
75
+ warmStarts += 1;
76
+ warmStream = start({
77
+ python,
78
+ script: DAEMON,
79
+ env: { ...process.env, ...env },
80
+ log: () => {},
81
+ onError: () => { warmStream = null; },
82
+ });
83
+ touchIdle();
84
+ return warmStream;
85
+ }
86
+
87
+ /* ------------------------------------------------- 链路选择 */
88
+
89
+ /**
90
+ * 试听走哪条链。`cfg.engine` 显式选了就不兜底(试听要如实,不是要"怎么都能响"):
91
+ * 'sapi' → 只走系统嗓
92
+ * 'edge' → edge-stream → edge-tts,都失败就报错(**不**静默换系统嗓)
93
+ * 留空(自动)→ 同上,最后多一步 SAPI 兜底,结果里报实际出声的引擎
94
+ */
95
+ export function planTtsTest(cfg, env = process.env) {
96
+ const explicit = cfg.engine === 'edge' || cfg.engine === 'sapi';
97
+ const policy = explicit ? cfg.engine : ttsPolicy(env);
98
+ if (policy === 'sapi') return { policy: 'sapi', chain: ['sapi'], explicit };
99
+ const bin = defaultEdgeTtsBin(env);
100
+ const python = bin ? pythonFor(bin) : null;
101
+ const chain = [];
102
+ if (python && existsSync(DAEMON)) chain.push('edge-stream');
103
+ if (bin) chain.push('edge-tts');
104
+ if (!explicit) chain.push('sapi');
105
+ return { policy: 'edge', chain, bin, python, explicit };
106
+ }
107
+
108
+ /* ------------------------------------------------- 执行 */
109
+
110
+ function interruptedResult(line, ms) {
111
+ return {
112
+ ok: false, engine: 'interrupted',
113
+ reason: 'interrupted', ms, firstMs: null, text: line,
114
+ };
115
+ }
116
+
117
+ /** 让 promise 和 AbortSignal 赛跑;被掐断时顺手 interrupt 通道(停声音)。 */
118
+ function raceInterrupt(promise, signal, stream) {
119
+ return new Promise((resolve) => {
120
+ let settled = false;
121
+ const done = (value) => { if (!settled) { settled = true; resolve(value); } };
122
+ if (signal?.aborted) return done({ ok: false, reason: 'interrupted' });
123
+ signal?.addEventListener('abort', () => {
124
+ try { stream?.interrupt(); } catch { /* 通道挂了就算了 */ }
125
+ done({ ok: false, reason: 'interrupted' });
126
+ }, { once: true });
127
+ promise.then(
128
+ (r) => done(r?.skipped ? { ok: false, reason: 'skipped' } : { ok: true, firstMs: r?.first ?? null }),
129
+ (e) => done({ ok: false, reason: String(e?.message ?? e).slice(0, 160) }),
130
+ );
131
+ return undefined;
132
+ });
133
+ }
134
+
135
+ /** 常驻通道念一句(参数随请求带,合成器不重启)。 */
136
+ async function streamOnce({ line, cfg, env, timeoutMs, signal, elapsed }) {
137
+ const stream = acquireTtsTestStream(env);
138
+ if (!stream) return { ok: false, reason: 'stream-unavailable' };
139
+ const params = {
140
+ voice: cfg.voice || undefined,
141
+ rate: Number(cfg.rate) || 0,
142
+ pitch: cfg.pitch || undefined,
143
+ volume: Number.isFinite(Number(cfg.volume)) ? Number(cfg.volume) : 100,
144
+ };
145
+ const startedAt = elapsed();
146
+ const r = await raceInterrupt(
147
+ stream.say(line, { timeoutMs: Math.max(5_000, timeoutMs - 5_000), params }),
148
+ signal,
149
+ stream,
150
+ );
151
+ if (!r.ok) return r;
152
+ // firstMs 要按「发出请求那一刻」起算(elapsed() 念完再取就虚高了)
153
+ return { ok: true, firstMs: r.firstMs === null ? null : startedAt + r.firstMs };
154
+ }
155
+
156
+ /**
157
+ * 试听一句。
158
+ *
159
+ * @param {{ text?: string, tts?: object, env?: object, timeoutMs?: number }} o
160
+ * `tts` = 面板当前值(不落盘;缺的键沿用已保存的 tts.json)。
161
+ * @returns {Promise<{ok:boolean, engine:string, ms:number, firstMs:number|null, text:string, reason?:string}>}
162
+ * `engine` 是**实际出声**的链(edge-stream / edge-tts / sapi);`firstMs` = 首声耗时;
163
+ * `reason:'interrupted'` = 被下一次试听顶掉了(不算失败)。
164
+ */
165
+ export async function runTtsTest({ text, tts, env = process.env, timeoutMs = 60_000 } = {}) {
166
+ const line = String(text ?? '').trim() || TTS_TEST_DEFAULT_TEXT;
167
+ if (line.length > TTS_TEST_MAX_TEXT) throw new Error(`试听文本太长(最多 ${TTS_TEST_MAX_TEXT} 字)`);
168
+ const cfg = effectiveTtsSettings(tts || {}, env);
169
+ const plan = planTtsTest(cfg, env);
170
+ const t0 = Date.now();
171
+ const ms = () => Date.now() - t0;
172
+
173
+ // **新顶旧**:有在飞的试听就先掐掉(和陪看发声同一原则,不排队、不叠着响)
174
+ if (currentRun) currentRun.interrupt();
175
+ const controller = new AbortController();
176
+ const run = {
177
+ interrupt() {
178
+ try { controller.abort(); } catch { /* 已经结束 */ }
179
+ try { warmStream?.interrupt(); } catch { /* 通道挂了就算了 */ }
180
+ },
181
+ };
182
+ currentRun = run;
183
+
184
+ try {
185
+ const params = {
186
+ voice: cfg.voice || null,
187
+ rate: Number(cfg.rate) || 0,
188
+ pitch: cfg.pitch || null,
189
+ volume: Number.isFinite(Number(cfg.volume)) ? Number(cfg.volume) : 100,
190
+ };
191
+ let reason = '';
192
+ for (const step of plan.chain) {
193
+ if (step === 'edge-stream') {
194
+ const r = await streamOnce({
195
+ line, cfg, env, timeoutMs, signal: controller.signal, elapsed: ms,
196
+ }).catch(() => null);
197
+ if (r?.ok) {
198
+ return {
199
+ ok: true, engine: 'edge-stream',
200
+ ms: ms(), firstMs: r.firstMs ?? ms(), text: line,
201
+ };
202
+ }
203
+ if (r?.reason === 'interrupted') return interruptedResult(line, ms());
204
+ reason = r?.reason || 'stream-failed';
205
+ } else if (step === 'edge-tts') {
206
+ const r = await speakViaEdgeTts(line, {
207
+ ...params, voice: params.voice || undefined, bin: plan.bin, timeoutMs,
208
+ signal: controller.signal,
209
+ }).catch(() => null);
210
+ if (r?.ok) {
211
+ return {
212
+ ok: true, engine: 'edge-tts',
213
+ ms: ms(), firstMs: ms(), text: line,
214
+ };
215
+ }
216
+ if (r?.reason === 'interrupted') return interruptedResult(line, ms());
217
+ reason = r?.reason || 'edge-failed';
218
+ } else {
219
+ const r = await speak(line, {
220
+ ...params, engine: 'sapi', timeoutMs, env, signal: controller.signal,
221
+ }).catch(() => null);
222
+ if (r?.ok) {
223
+ return {
224
+ ok: true, engine: 'sapi',
225
+ ms: ms(), firstMs: ms(), text: line,
226
+ };
227
+ }
228
+ if (r?.reason === 'interrupted') return interruptedResult(line, ms());
229
+ reason = r?.reason || 'sapi-failed';
230
+ }
231
+ }
232
+ return {
233
+ ok: false,
234
+ engine: plan.chain.at(-1) || 'none',
235
+ reason: reason || 'edge-tts-not-installed',
236
+ ms: ms(),
237
+ firstMs: null,
238
+ text: line,
239
+ };
240
+ } finally {
241
+ if (currentRun === run) currentRun = null;
242
+ }
243
+ }