边生成边读:内核流式路由 + 安卓 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:
@@ -53,6 +53,7 @@ import {
|
||||
import { listModels } from './providers.mjs';
|
||||
import {
|
||||
synthesize,
|
||||
synthesizeStream,
|
||||
transcribe,
|
||||
speechState,
|
||||
VOICE_OPTIONS,
|
||||
@@ -99,6 +100,63 @@ function cors(res) {
|
||||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
|
||||
}
|
||||
|
||||
/**
|
||||
* 边合成边下发音频。
|
||||
*
|
||||
* ★ 关键设计:**先把第一块取出来,再发响应头**。
|
||||
* 合成失败(Key 不对、音色不存在……)基本都发生在第一块之前,
|
||||
* 这时候还没发头,就能照常返回 JSON 错误,客户端拿得到具体原因并退回系统 TTS。
|
||||
* 要是先把头发出去,就只能截断连接,客户端看到的是"啥也没说就断了"。
|
||||
*
|
||||
* 中途失败就只能截断 —— 头都发出去了,改不了状态码。
|
||||
* 客户端会把已收到的部分播完,不会崩。
|
||||
*/
|
||||
async function streamTts(req, res, text, settings) {
|
||||
// 引擎是"设备自带"时不走流式:那种情况内核根本不参与合成,
|
||||
// 直接告诉客户端"这轮该用系统 TTS",别让它收到一个莫名其妙的空音频错误。
|
||||
if (speechState(settings).ttsEngine === 'system') {
|
||||
sendJson(res, 200, { ok: false, engine: 'system', error: '当前是系统朗读,不用云端合成' });
|
||||
return;
|
||||
}
|
||||
|
||||
const gen = synthesizeStream(text, settings);
|
||||
let first;
|
||||
try {
|
||||
first = await gen.next();
|
||||
} catch (err) {
|
||||
sendJson(res, 200, { ok: false, error: err.message });
|
||||
return;
|
||||
}
|
||||
if (first.done) {
|
||||
sendJson(res, 200, { ok: false, error: '没有要朗读的内容' });
|
||||
return;
|
||||
}
|
||||
|
||||
cors(res);
|
||||
res.writeHead(200, {
|
||||
'Content-Type': first.value.mime || 'audio/L16',
|
||||
'Cache-Control': 'no-store',
|
||||
'X-Audio-Stream': '1',
|
||||
// 不设 Content-Length,Node 会自动用 chunked
|
||||
});
|
||||
res.write(Buffer.from(first.value.data));
|
||||
|
||||
try {
|
||||
for (;;) {
|
||||
const next = await gen.next();
|
||||
if (next.done) break;
|
||||
if (!res.write(Buffer.from(next.value.data))) {
|
||||
// 背压:等 drain 再继续,否则慢客户端会把内存撑爆
|
||||
await new Promise((resolve) => res.once('drain', resolve));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 已经出了几块,头改不了,只能截断(见上面注释)
|
||||
} finally {
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
|
||||
async function readBody(req, limit = 4 * 1024 * 1024) {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
@@ -392,6 +450,17 @@ async function handleApi(req, res, url) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pathname === '/api/tts/stream' && method === 'POST') {
|
||||
// 边合成边下发:音频块一到就 write,客户端能立刻开始播,
|
||||
// 不用等整段合成完(实测长句首块 ~0.9s 到、末块 ~2.7s 到)。
|
||||
let body = {};
|
||||
try {
|
||||
body = await readBody(req);
|
||||
} catch { /* 空 body 由 synthesizeStream 自己报错 */ }
|
||||
await streamTts(req, res, body.text, readSettings());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pathname === '/api/stt' && method === 'POST') {
|
||||
// 音频是原始字节(不套 JSON/base64):省一次编解码,客户端录完直接发
|
||||
let audio;
|
||||
|
||||
@@ -153,7 +153,126 @@ export async function synthesize(text, settings) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 豆包语音 V3 合成 —— "只要一个 API Key" 的那条路。
|
||||
* 流式合成:边生成边把音频块吐出来(异步生成器)。
|
||||
*
|
||||
* 为什么需要它:整段合成完再播,长回复要等好几秒才出声。实测火山 v3 接口
|
||||
* **本身就是边生成边下发的**(一段 60 字的文本,首块 1.1s 到、末块 6.0s 到,
|
||||
* 跨度 5 秒),所以只要这边不攒、跟着往下传,播放端就能"边生成边读"。
|
||||
*
|
||||
* ★ 不需要 WebSocket。火山确实有 wss://…/tts/bidirection,但那是另一套
|
||||
* 二进制私有协议;HTTP 这条路已经能流式,何必多写一层帧解析。
|
||||
*
|
||||
* yield { mime, data: Buffer }。只支持云端引擎 —— system 引擎归系统 TTS 管,
|
||||
* 内核根本不参与合成(调用方自己判断 engine 是不是 system)。
|
||||
*/
|
||||
export async function* synthesizeStream(text, settings) {
|
||||
const speech = speechOf(settings);
|
||||
const engine = String(speech.ttsEngine || 'system').toLowerCase();
|
||||
const content = stripMarkdown(text);
|
||||
if (!content) throw new SpeechError('没有要朗读的内容');
|
||||
const speed = Math.min(Math.max(Number(speech.ttsSpeed) || 1.0, 0.2), 3.0);
|
||||
|
||||
if (engine === 'volcv3') {
|
||||
yield* streamVolcV3(content, speech, speed);
|
||||
return;
|
||||
}
|
||||
// 其他引擎没有流式接口,退回"整段合成再一次给"
|
||||
const result = await synthesize(text, settings);
|
||||
if (result.audio) {
|
||||
yield { mime: result.mime || 'audio/mpeg', data: Buffer.from(result.audio, 'base64') };
|
||||
}
|
||||
}
|
||||
|
||||
/** 火山 v3 的流式读取:逐行 NDJSON,每行一段 base64 音频,拿到就 yield */
|
||||
async function* streamVolcV3(text, speech, speed) {
|
||||
const apiKey = String(speech.volcApiKey || '').trim();
|
||||
const speaker = String(speech.ttsVoice || '').trim() || 'zh_female_vv_uranus_bigtts';
|
||||
let format = String(speech.volcEncoding || 'pcm').trim() || 'pcm';
|
||||
if (!['mp3', 'wav', 'ogg_opus', 'pcm'].includes(format)) format = 'pcm';
|
||||
|
||||
if (!apiKey) {
|
||||
throw new SpeechError(
|
||||
'豆包语音 V3 需要一个 API Key:语音控制台 →(左侧)API Key → 创建 API Key。'
|
||||
+ '注意不是方舟的 Key —— 方舟 Key 打这个接口会被判 401。',
|
||||
);
|
||||
}
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(VOLC_V3_TTS_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Api-Key': apiKey,
|
||||
'X-Api-Resource-Id': VOLC_V3_RESOURCE_ID,
|
||||
'X-Control-Require-Usage-Tokens-Return': '*',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
req_params: {
|
||||
text,
|
||||
speaker,
|
||||
audio_params: {
|
||||
format,
|
||||
sample_rate: 24000,
|
||||
speech_rate: Math.round((speed - 1.0) * 100),
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
} catch (err) {
|
||||
throw new SpeechError(`连不上火山 V3:${err.message}`);
|
||||
}
|
||||
|
||||
const mime = VOLC_MIME[format] || 'audio/L16';
|
||||
if (!res.ok) {
|
||||
const detail = (await res.text().catch(() => '')).slice(0, 300);
|
||||
throw new SpeechError(`HTTP ${res.status} ${detail}`);
|
||||
}
|
||||
|
||||
// ★ 关键就是这里不 await res.text():按行读,火山下发一行我们解一行、yield 一行
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buf = '';
|
||||
let error = null;
|
||||
let gotAny = false;
|
||||
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buf += decoder.decode(value, { stream: true });
|
||||
let nl;
|
||||
while ((nl = buf.indexOf('\n')) >= 0) {
|
||||
const line = buf.slice(0, nl).trim();
|
||||
buf = buf.slice(nl + 1);
|
||||
if (!line) continue;
|
||||
let item;
|
||||
try {
|
||||
item = JSON.parse(line);
|
||||
} catch {
|
||||
continue; // NDJSON 之外的行(心跳/空行)跳过
|
||||
}
|
||||
const code = item.code;
|
||||
if (typeof item.data === 'string' && item.data) {
|
||||
gotAny = true;
|
||||
yield { mime, data: Buffer.from(item.data, 'base64') };
|
||||
}
|
||||
if (code === 20000000) {
|
||||
break;
|
||||
}
|
||||
if (typeof code === 'number' && code > 0) {
|
||||
error = `code=${code} ${item.message || item.msg || ''}`.trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (error) break;
|
||||
}
|
||||
|
||||
if (error) throw new SpeechError(`火山 V3 失败:${error}`);
|
||||
if (!gotAny) throw new SpeechError('火山 V3 没返回音频数据');
|
||||
}
|
||||
|
||||
/**
|
||||
* 豆包语音 V3 合成(一次性,非流式)—— "只要一个 API Key" 的那条路。
|
||||
*
|
||||
* 和 V1 的区别(用户最容易搞混的地方):
|
||||
* - **只要一个 API Key**(语音控制台 → API Key 管理),不需要 AppID / Access Token;
|
||||
|
||||
Reference in New Issue
Block a user