边生成边读:内核流式路由 + 安卓 AudioTrack 边收边播
接上一条(内核已有 synthesize_stream,实测厂商接口本身就在流式下发)。 这次把剩下三步做完,整条链路打通。 【内核路由 /api/tts/stream】 两份内核各一份,都是"音频块一到就写出去",不是攒完再发。 新增 scripts/verify-tts-route.mjs 起内核实测:Node 首块 964ms / 末块 2797ms, Python 首块 997ms / 末块 2571ms,都判定为流式。 ★ 一个关键设计:**先把第一块取出来,再发响应头**。 合成失败(Key 不对、音色不存在)基本都发生在第一块之前,这时候还没发头, 就能照常返回 JSON 错误,客户端拿得到具体原因并退回系统 TTS。 要是先把头发出去就只能截断连接,用户看到的是"啥也没说就断了"。 中途失败没法改状态码,只能截断,客户端会把已收到的部分播完。 另外引擎是"设备自带"时直接返回"这轮该用系统 TTS",不走流式 —— 那种情况内核根本不参与合成,否则客户端会收到一个莫名其妙的空音频错误。 【安卓 AudioTrack 边收边播】 - PcmPlayer 从 MODE_STATIC 改成 MODE_STREAM:write() 多少播多少, 缓冲区满时 write 会阻塞,天然形成背压,不用自己控速。 - 采样率固定 24000(火山大模型音色的输出率)。写成录音那个 16000 会变调。 - 收尾用 drainAndRelease:不能立刻 stop(),MODE_STREAM 下 stop() 会把缓冲区里 还没播的音频丢掉,最后半句就没了。 - KernelClient.streamTts 返回 Response 而不是 ByteArray —— 一旦在那里面 readBytes() 就退回成"整段收完再播",正是要避免的。 ★ 写的时候差点犯一个致命错误:okio 的 readByteArray() 不带参数是 "一直读到流结束",写成那样等于整段收完再播,流式白做。必须用 read(buffer, n)。 【验了最担心的一点】 PC 上能流式不代表手机上能 —— Python 的 urllib 在有些环境下会缓冲。 所以专门在真机环境(模拟器上的 Chaquopy 进程)里量了一遍: 首块 750ms / 末块 2261ms,23 块 / 422KB → 安卓上确实是边读边给。 新增 scripts/verify-tts-device.mjs 把这条固化成验收。 (最初写成调 adb shell 的 python3,设备上根本没这个命令;改成走内核自己的 python_run,在同一进程里直接调 synthesize_stream,反而更贴近要验的东西。) 【顺带修的】 /api/speech 的 voices 里漏了 volcv3,和 /api/state 那处不一致 —— 界面读那个接口时 V3 会一个音色都选不出来。 回归:Markdown 剥离对拍 19/19、语音验收 36/36 ×2、流式路由两份内核都过、 设备端 Chaquopy 流式通过。
This commit is contained in:
114
scripts/verify-tts-device.mjs
Normal file
114
scripts/verify-tts-device.mjs
Normal file
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* 在真机/模拟器上测 App 内核的流式朗读:/api/tts/stream。
|
||||
*
|
||||
* 这一步专门验 Chaquopy 里的 Python:urllib 的 urlopen().readline() 在安卓上
|
||||
* 到底是"边读边给"还是"先缓冲一大段"。PC 上测过不代表手机上一样 ——
|
||||
* 如果它缓冲,那整个"边生成边读"在安卓端就是假的。
|
||||
*
|
||||
* 跑法: VOLC_KEY=xxx node scripts/verify-tts-device.mjs emulator-5556
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const SERIAL = process.argv[2] || 'emulator-5556';
|
||||
const KEY = (process.env.VOLC_KEY || '').trim();
|
||||
const ADB = process.env.ADB || 'C:\\Android\\Sdk\\platform-tools\\adb.exe';
|
||||
|
||||
if (!KEY) {
|
||||
console.log(' 需要 VOLC_KEY 环境变量');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const sh = (cmd, timeout = 180000) =>
|
||||
spawnSync(ADB, ['-s', SERIAL, 'shell', cmd], { encoding: 'utf8', timeout, maxBuffer: 16 * 1024 * 1024 });
|
||||
|
||||
// ① 把语音引擎切到 volcv3 并写入 API Key(走内核自己的接口,不碰应用私有文件)
|
||||
const patch = JSON.stringify({
|
||||
speech: {
|
||||
ttsEngine: 'volcv3',
|
||||
volcApiKey: KEY,
|
||||
ttsVoice: 'zh_female_vv_uranus_bigtts',
|
||||
volcEncoding: 'pcm',
|
||||
ttsSpeed: 1.0,
|
||||
},
|
||||
});
|
||||
const b64 = Buffer.from(patch, 'utf8').toString('base64');
|
||||
|
||||
let r = sh(`echo '${b64}' | base64 -d > /data/local/tmp/sp.json; curl -s --max-time 20 -X PUT -H 'Content-Type: application/json' -d @/data/local/tmp/sp.json http://127.0.0.1:5199/api/settings | head -c 200`);
|
||||
console.log(' ① 写入语音配置:', (r.stdout || '').replace(/\s+/g, ' ').slice(0, 120));
|
||||
|
||||
// ② 确认内核认到了
|
||||
r = sh(`curl -s --max-time 15 http://127.0.0.1:5199/api/speech`);
|
||||
try {
|
||||
const st = JSON.parse(r.stdout || '{}');
|
||||
console.log(` ② 引擎=${st.speech?.ttsEngine} 有Key=${st.speech?.hasVolcApiKey} 音色=${st.speech?.ttsVoice}`);
|
||||
} catch {
|
||||
console.log(' ② 读状态失败:', (r.stdout || '').slice(0, 160));
|
||||
}
|
||||
|
||||
// ③ 在 **App 自己的 Python 进程里**直接跑流式合成并计时。
|
||||
//
|
||||
// 为什么不走 adb shell 的 python3:设备上根本没有那个命令(试过,报
|
||||
// "python3: inaccessible or not found")。而且就算有,那也不是我们要验的环境 ——
|
||||
// 真正要验的是 Chaquopy 里的 urllib 到底缓不缓冲。所以用内核自己的 python_run
|
||||
// 工具,在同一进程里直接调 speech.synthesize_stream()。
|
||||
const TEXT = '人工智能正在改变我们生活的方方面面。从早上叫醒我们的智能音箱,到通勤路上推荐路线的导航软件。';
|
||||
const probe = [
|
||||
'import time, sys',
|
||||
"sys.path.insert(0, '/data/user/0/com.doubao.lynxclone/files/kernel')",
|
||||
'import speech',
|
||||
`settings = {'speech': {'ttsEngine': 'volcv3', 'volcApiKey': ${JSON.stringify(KEY)},`,
|
||||
" 'ttsVoice': 'zh_female_vv_uranus_bigtts', 'volcEncoding': 'pcm', 'ttsSpeed': 1.0}}",
|
||||
`text = ${JSON.stringify(TEXT)}`,
|
||||
't0 = time.time()',
|
||||
'first = None; last = None; total = 0; chunks = 0',
|
||||
'for mime, chunk in speech.synthesize_stream(text, settings):',
|
||||
' chunks += 1; total += len(chunk)',
|
||||
' now = time.time() - t0',
|
||||
' if first is None: first = now',
|
||||
' last = now',
|
||||
"print('MIME', mime)",
|
||||
"print('CHUNKS', chunks, 'BYTES', total)",
|
||||
"print('FIRST_MS', round((first or 0) * 1000))",
|
||||
"print('LAST_MS', round((last or 0) * 1000))",
|
||||
].join('\n');
|
||||
|
||||
const probeFile = path.join(os.tmpdir(), `doubao-devprobe-${Date.now()}.json`);
|
||||
fs.writeFileSync(probeFile, JSON.stringify({ code: probe }), 'utf8');
|
||||
|
||||
const tool = spawnSync(process.execPath, [path.join(ROOT, 'scripts', 'device-tool.mjs'), SERIAL, 'python_run', `@${probeFile}`], {
|
||||
encoding: 'utf8',
|
||||
timeout: 240000,
|
||||
maxBuffer: 16 * 1024 * 1024,
|
||||
});
|
||||
try { fs.rmSync(probeFile, { force: true }); } catch { /* 忽略 */ }
|
||||
|
||||
const out = `${tool.stdout || ''}${tool.stderr || ''}`;
|
||||
const pick = (name) => {
|
||||
const m = out.match(new RegExp(`${name}\\s+([0-9]+)`));
|
||||
return m ? Number(m[1]) : 0;
|
||||
};
|
||||
// 设备的输出是 JSON 转义过的(换行是字面的 \n),所以 \S+ 会把后面的内容一起吞掉,
|
||||
// 这里用 [^\s\\]+ 明确排除反斜杠
|
||||
const mimeMatch = out.match(/MIME\s+([^\s\\]+)/);
|
||||
const first = pick('FIRST_MS');
|
||||
const last = pick('LAST_MS');
|
||||
const chunks = pick('CHUNKS');
|
||||
const bytes = pick('BYTES');
|
||||
|
||||
console.log(' ③ 设备端(Chaquopy 同进程)流式测量:');
|
||||
if (!first) {
|
||||
console.log(' [FAIL] 没拿到测量结果');
|
||||
console.log(` ${out.replace(/\s+/g, ' ').slice(0, 400)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const streamed = first < last * 0.6;
|
||||
console.log(` Content-Type=${mimeMatch ? mimeMatch[1] : '(未知)'}`);
|
||||
console.log(` ${chunks} 块 / ${bytes} 字节`);
|
||||
console.log(` 首块 ${first}ms 末块 ${last}ms ${streamed ? '[OK] 安卓上也是流式' : '[FAIL] 被缓冲了'}`);
|
||||
process.exit(streamed ? 0 : 1);
|
||||
|
||||
141
scripts/verify-tts-route.mjs
Normal file
141
scripts/verify-tts-route.mjs
Normal file
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* 验收 /api/tts/stream:确认它真的是"边合成边下发",而不是攒完再一次给。
|
||||
*
|
||||
* 量法和之前量厂商接口一样:记录第一块和最后一块的到达时刻。
|
||||
* 首块明显早于末块 = 流式;两者几乎相等 = 中间被谁攒住了。
|
||||
*
|
||||
* 跑法:
|
||||
* VOLC_KEY=xxx node scripts/verify-tts-route.mjs py
|
||||
* VOLC_KEY=xxx node scripts/verify-tts-route.mjs node
|
||||
*
|
||||
* 没给 VOLC_KEY 就跳过(这条要打真厂商接口,不能拿 mock 假装)。
|
||||
*/
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const KIND = process.argv[2] === 'node' ? 'node' : 'py';
|
||||
const KEY = (process.env.VOLC_KEY || '').trim();
|
||||
const PY = process.env.PYTHON || 'C:\\Python313\\python.exe';
|
||||
const PORT = KIND === 'py' ? 5391 : 5392;
|
||||
|
||||
if (!KEY) {
|
||||
console.log(' 需要 VOLC_KEY 环境变量(这条会打真接口,不能 mock)');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
// 独立的临时数据目录:不动开发用的那份配置
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), `doubao-tts-${KIND}-`));
|
||||
fs.writeFileSync(
|
||||
path.join(dataDir, 'settings.json'),
|
||||
JSON.stringify({
|
||||
speech: {
|
||||
ttsEngine: 'volcv3',
|
||||
volcApiKey: KEY,
|
||||
ttsVoice: 'zh_female_vv_uranus_bigtts',
|
||||
volcEncoding: 'pcm',
|
||||
ttsSpeed: 1.0,
|
||||
},
|
||||
}),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
const TEXT = '人工智能正在改变我们生活的方方面面。从早上叫醒我们的智能音箱,'
|
||||
+ '到通勤路上推荐路线的导航软件,再到工作中帮我们整理资料的助手。';
|
||||
|
||||
/** 起内核,等它就绪 */
|
||||
function startKernel() {
|
||||
const env = { ...process.env, PYTHONIOENCODING: 'utf-8' };
|
||||
let child;
|
||||
if (KIND === 'py') {
|
||||
child = spawn(PY, [path.join(ROOT, 'android', 'kernel', 'main.py')], {
|
||||
env: { ...env, DOUBAO_DATA: dataDir, DOUBAO_PORT: String(PORT) },
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
} else {
|
||||
child = spawn(process.execPath, [path.join(ROOT, 'server', 'src', 'index.mjs')], {
|
||||
env: { ...env, DOUBAO_DATA: dataDir, PORT: String(PORT) },
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
}
|
||||
child.stdout.on('data', () => {});
|
||||
child.stderr.on('data', () => {});
|
||||
return child;
|
||||
}
|
||||
|
||||
async function waitReady(timeoutMs = 25000) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const r = await fetch(`http://127.0.0.1:${PORT}/api/health`, { signal: AbortSignal.timeout(2000) });
|
||||
if (r.ok) return true;
|
||||
} catch { /* 还没起来 */ }
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
let child;
|
||||
let failed = 0;
|
||||
try {
|
||||
child = startKernel();
|
||||
if (!(await waitReady())) {
|
||||
console.log(` [FAIL] ${KIND} 内核没起来(端口 ${PORT})`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(` ${KIND} 内核已就绪,端口 ${PORT}`);
|
||||
|
||||
const t0 = Date.now();
|
||||
const res = await fetch(`http://127.0.0.1:${PORT}/api/tts/stream`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text: TEXT }),
|
||||
});
|
||||
|
||||
if (res.status !== 200) {
|
||||
console.log(` [FAIL] HTTP ${res.status}`);
|
||||
failed += 1;
|
||||
} else if ((res.headers.get('content-type') || '').includes('json')) {
|
||||
// 第一块之前就失败了 → 这里会是一个正常 JSON,带具体原因(设计如此)
|
||||
const j = await res.json();
|
||||
console.log(` [FAIL] 内核返回错误:${j.error}`);
|
||||
failed += 1;
|
||||
} else {
|
||||
console.log(` Content-Type: ${res.headers.get('content-type')}`);
|
||||
const reader = res.body.getReader();
|
||||
let firstAt = 0;
|
||||
let lastAt = 0;
|
||||
let total = 0;
|
||||
let chunks = 0;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value || !value.length) continue;
|
||||
chunks += 1;
|
||||
total += value.length;
|
||||
if (!firstAt) firstAt = Date.now() - t0;
|
||||
lastAt = Date.now() - t0;
|
||||
}
|
||||
|
||||
if (!total) {
|
||||
console.log(' [FAIL] 一个字节都没收到');
|
||||
failed += 1;
|
||||
} else {
|
||||
const streamed = firstAt < lastAt * 0.6;
|
||||
if (!streamed) failed += 1;
|
||||
console.log(` ${chunks} 块 / ${total} 字节`);
|
||||
console.log(` 首块 ${firstAt}ms 末块 ${lastAt}ms ${streamed ? '[OK] 边合成边下发' : '[FAIL] 被攒住了'}`);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (child) child.kill();
|
||||
// 内核可能起了子进程,补一刀
|
||||
if (KIND === 'node') spawnSync(process.execPath, ['-e', 'process.exit(0)']);
|
||||
try { fs.rmSync(dataDir, { recursive: true, force: true }); } catch { /* 忽略 */ }
|
||||
}
|
||||
|
||||
console.log(failed ? '\n 失败' : '\n 通过');
|
||||
process.exit(failed ? 1 : 0);
|
||||
Reference in New Issue
Block a user