用户报"读一半就不读了"。先量上游确认不是它截断 —— 结果上游完全正常:
42 字 → 375304 字节 → 7.8 秒音频
210 字 → 1861802 字节 → 38.8 秒音频
840 字 → 6856642 字节 → 142.8 秒音频
(PCM 24kHz 单声道 16bit = 48000 字节/秒)
所以问题在客户端,而且数字对得严丝合缝:一段 210 字的回答有 38.8 秒音频,
而 PcmPlayer.drainAndRelease 里是个**写死的 15 秒死线** ——
val deadline = System.currentTimeMillis() + 15_000
while (...) { if (played >= totalFrames) break; sleep(50) }
stop() // ← 超时就 stop(),把还没播完的音频砍掉
15 秒一到就 stop(),用户听到的就是"读一半就不读了"。回复越长砍得越早。
修:按音频长度算等待时间,不再写死。
expectMs = totalFrames * 1000 / SAMPLE_RATE + 5000
多给 5 秒余量应付播放头更新延迟。用户中途点停止时,playbackHeadPosition
会抛(轨道已释放)→ break,照样立刻收工。
顺带给 mock 加了 MOCK_REPLY_CHARS:**有一类 bug 只有长内容才暴露**
(这次的"播一半被砍"就是),拿短回复测永远是绿的。
MOCK_REPLY_CHARS=400 node scripts/mock-llm.mjs
关于验证:写了个自动量"播放时长"的脚本,但这台设备的 UI 自动化不稳
(打字/点击经常打空,消息压根发不出去),测出来的"没播放"是假的,
所以删掉了 —— 与其留个会误报的验收脚本,不如不留。
这次的证据是"上游时长 vs 客户端死线"的硬数字对比,很确定;
真机上播完没播完还得靠耳朵确认。
附:测试过程中临时改过设备上的 baseUrl/autoRead,跑完已完整恢复
(provider/baseUrl/model/Key/昵称/18 个会话/语音 Key 都核对过了)。
217 lines
8.6 KiB
JavaScript
217 lines
8.6 KiB
JavaScript
/**
|
||
* 假的 OpenAI 兼容服务 + 假的火山语音服务,用来端到端验证内核(不消耗任何真实额度)。
|
||
*
|
||
* 对话:第一轮返回 tool_call(calc),第二轮根据工具结果流式回答。
|
||
* 语音:/v1/audio/speech 回一段真 WAV;/v1/audio/transcriptions 回固定文字;
|
||
* 还顺手把收到的请求形状打出来,用来核对"我们到底发了什么头/字段"。
|
||
*/
|
||
import http from 'node:http';
|
||
|
||
const PORT = Number(process.env.MOCK_PORT || 5299);
|
||
|
||
/**
|
||
* 回复长度(字符数)。默认是原来那段短回答。
|
||
*
|
||
* 为什么做成可配:有一类 bug **只有长内容才暴露** —— 比如朗读播到一半被砍
|
||
* (收尾死线写死 15 秒,而一段 210 字的回答有 38.8 秒音频)。
|
||
* 拿短回复测永远是绿的,必须能造出长回复。
|
||
*
|
||
* MOCK_REPLY_CHARS=400 node scripts/mock-llm.mjs
|
||
*/
|
||
const REPLY_CHARS = Number(process.env.MOCK_REPLY_CHARS || 0);
|
||
|
||
/** 造一段指定字数的中文回复 */
|
||
function longReply(chars) {
|
||
const unit = '人工智能正在改变我们生活的方方面面,从早上叫醒我们的智能音箱,'
|
||
+ '到通勤路上推荐路线的导航软件,再到工作中帮我们整理资料的助手。';
|
||
let out = '';
|
||
while (out.length < chars) out += unit;
|
||
return out.slice(0, chars);
|
||
}
|
||
|
||
function sse(res, obj) {
|
||
res.write(`data: ${JSON.stringify(obj)}\n\n`);
|
||
}
|
||
|
||
/** 造一段 0.3 秒的正弦波 WAV(16000Hz 单声道 16bit),用来验证播放链路 */
|
||
function makeWav(seconds = 0.3, freq = 440) {
|
||
const rate = 16000;
|
||
const n = Math.floor(rate * seconds);
|
||
const data = Buffer.alloc(n * 2);
|
||
for (let i = 0; i < n; i += 1) {
|
||
data.writeInt16LE(Math.round(Math.sin((2 * Math.PI * freq * i) / rate) * 8000), i * 2);
|
||
}
|
||
const header = Buffer.alloc(44);
|
||
header.write('RIFF', 0);
|
||
header.writeUInt32LE(36 + data.length, 4);
|
||
header.write('WAVE', 8);
|
||
header.write('fmt ', 12);
|
||
header.writeUInt32LE(16, 16);
|
||
header.writeUInt16LE(1, 20);
|
||
header.writeUInt16LE(1, 22);
|
||
header.writeUInt32LE(rate, 24);
|
||
header.writeUInt32LE(rate * 2, 28);
|
||
header.writeUInt16LE(2, 32);
|
||
header.writeUInt16LE(16, 34);
|
||
header.write('data', 36);
|
||
header.writeUInt32LE(data.length, 40);
|
||
return Buffer.concat([header, data]);
|
||
}
|
||
|
||
const server = http.createServer(async (req, res) => {
|
||
const url = req.url || '';
|
||
|
||
/* ---------------- 语音合成(OpenAI 兼容 /audio/speech)---------------- */
|
||
if (url.startsWith('/v1/audio/speech')) {
|
||
const chunks = [];
|
||
for await (const c of req) chunks.push(c);
|
||
let body = {};
|
||
try {
|
||
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
||
} catch { /* 下面照常回音频 */ }
|
||
console.log(
|
||
`[mock][tts] auth=${req.headers.authorization ? '有' : '无'} model=${body.model} ` +
|
||
`voice=${body.voice} speed=${body.speed} fmt=${body.response_format} ` +
|
||
`文本=${JSON.stringify(String(body.input || '').slice(0, 30))}`,
|
||
);
|
||
const wav = makeWav(0.3, 520);
|
||
res.writeHead(200, { 'Content-Type': 'audio/wav', 'Content-Length': wav.length }).end(wav);
|
||
return;
|
||
}
|
||
|
||
/* ---------------- 语音合成(火山 v1 /api/v1/tts)---------------- */
|
||
if (url.startsWith('/api/v1/tts')) {
|
||
const chunks = [];
|
||
for await (const c of req) chunks.push(c);
|
||
let body = {};
|
||
try {
|
||
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
||
} catch { /* 忽略 */ }
|
||
const auth = req.headers.authorization || '';
|
||
console.log(
|
||
`[mock][volc-tts] Authorization=${JSON.stringify(auth)} ` +
|
||
`app.appid=${body.app?.appid} app.token=${body.app?.token ? '有' : '无'} app.cluster=${body.app?.cluster} ` +
|
||
`audio.voice_type=${body.audio?.voice_type} audio.encoding=${body.audio?.encoding} ` +
|
||
`audio.speed_ratio=${body.audio?.speed_ratio} ` +
|
||
`request.text_type=${body.request?.text_type} request.operation=${body.request?.operation} ` +
|
||
`request.reqid=${body.request?.reqid ? '有' : '无'} text=${JSON.stringify(String(body.request?.text || '').slice(0, 20))}`,
|
||
);
|
||
// 校验鉴权头是不是文档要求的分号形式 —— 这正是最容易写错的地方
|
||
const semicolonOk = auth.startsWith('Bearer;');
|
||
if (!semicolonOk) {
|
||
res.writeHead(200, { 'Content-Type': 'application/json' }).end(
|
||
JSON.stringify({ code: 3001, message: '鉴权头格式不对:必须是 Bearer;<token>(分号)' }),
|
||
);
|
||
return;
|
||
}
|
||
const wav = makeWav(0.3, 660);
|
||
res.writeHead(200, { 'Content-Type': 'application/json' }).end(
|
||
JSON.stringify({ code: 3000, message: 'Success', reqid: body.request?.reqid, data: wav.toString('base64') }),
|
||
);
|
||
return;
|
||
}
|
||
|
||
/* ---------------- 语音识别(OpenAI 兼容 /audio/transcriptions)---------------- */
|
||
if (url.startsWith('/v1/audio/transcriptions')) {
|
||
const chunks = [];
|
||
for await (const c of req) chunks.push(c);
|
||
const raw = Buffer.concat(chunks);
|
||
const ctype = req.headers['content-type'] || '';
|
||
const boundary = (ctype.match(/boundary=(.+)$/) || [])[1] || '';
|
||
const text = raw.toString('latin1');
|
||
const model = (text.match(/name="model"\r\n\r\n([^\r]*)/) || [])[1] || '?';
|
||
const hasFile = text.includes('name="file"') && text.includes('filename=');
|
||
console.log(
|
||
`[mock][stt] auth=${req.headers.authorization ? '有' : '无'} boundary=${boundary ? '有' : '无'} ` +
|
||
`model=${model} 带文件=${hasFile} 体积=${raw.length}`,
|
||
);
|
||
res.writeHead(200, { 'Content-Type': 'application/json' }).end(
|
||
JSON.stringify({ text: '这是语音识别的模拟结果' }),
|
||
);
|
||
return;
|
||
}
|
||
|
||
if (!url.startsWith('/v1/chat/completions')) {
|
||
res.writeHead(404).end('nope');
|
||
return;
|
||
}
|
||
const chunks = [];
|
||
for await (const c of req) chunks.push(c);
|
||
// 别让一条坏请求把整个 mock 打死:壳脚本/手敲 curl 很容易发出不合法 JSON,
|
||
// 之前没防这一下,mock 直接退出,界面那边只看到 "Remote end closed connection"。
|
||
let body;
|
||
try {
|
||
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
||
} catch (e) {
|
||
console.log('[mock] 请求体不是合法 JSON,已忽略:', e.message);
|
||
res.writeHead(400, { 'Content-Type': 'application/json' }).end('{"error":"bad json"}');
|
||
return;
|
||
}
|
||
const messages = body.messages || [];
|
||
const toolMsg = messages.findLast?.((m) => m.role === 'tool');
|
||
const hasTools = Array.isArray(body.tools) && body.tools.length > 0;
|
||
|
||
console.log(
|
||
`[mock] model=${body.model} tools=${body.tools?.length || 0} msgs=${messages.length} ` +
|
||
`temperature=${body.temperature} thinking=${JSON.stringify(body.thinking)} ` +
|
||
`reasoning_effort=${body.reasoning_effort}`,
|
||
);
|
||
|
||
res.writeHead(200, {
|
||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||
'Cache-Control': 'no-cache, no-transform',
|
||
Connection: 'keep-alive',
|
||
});
|
||
|
||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||
|
||
if (!toolMsg && hasTools) {
|
||
// 第一轮:要求调用 calc 工具
|
||
const args = JSON.stringify({ expression: '(1+2)*3' });
|
||
sse(res, {
|
||
choices: [{
|
||
delta: {
|
||
tool_calls: [{
|
||
index: 0,
|
||
id: 'call_mock_1',
|
||
type: 'function',
|
||
function: { name: 'calc', arguments: args },
|
||
}],
|
||
},
|
||
}],
|
||
});
|
||
await sleep(120);
|
||
sse(res, { choices: [{ delta: {}, finish_reason: 'tool_calls' }] });
|
||
res.write('data: [DONE]\n\n');
|
||
res.end();
|
||
return;
|
||
}
|
||
|
||
// 第二轮:先吐一段思维链(reasoning_content),再给最终回答
|
||
const thinking = [
|
||
'用户要算 (1+2)*3。',
|
||
'我需要先调用计算工具,避免自己算错。',
|
||
'工具返回的表达式是 (1+2)*3,结果是 9。',
|
||
'把结果解释给用户,并说明这条链路是端到端跑通的。',
|
||
].join('');
|
||
for (const ch of thinking) {
|
||
sse(res, { choices: [{ delta: { reasoning_content: ch } }] });
|
||
await sleep(8);
|
||
}
|
||
|
||
const toolText = toolMsg ? String(toolMsg.content) : '(没拿到工具结果)';
|
||
const answer = REPLY_CHARS > 0
|
||
? longReply(REPLY_CHARS)
|
||
: `我用 calc 工具算了一下:${toolText}\n\n所以 (1+2)*3 = 9。这条回答是端到端跑通的:界面 → 内核 → 工具调用 → 流式返回。`;
|
||
for (const ch of answer) {
|
||
sse(res, { choices: [{ delta: { content: ch } }] });
|
||
await sleep(12);
|
||
}
|
||
sse(res, { choices: [{ delta: {}, finish_reason: 'stop' }] });
|
||
sse(res, { usage: { prompt_tokens: 100, completion_tokens: 60, total_tokens: 160 }, choices: [] });
|
||
res.write('data: [DONE]\n\n');
|
||
res.end();
|
||
});
|
||
|
||
server.listen(PORT, '127.0.0.1', () => console.log(`[mock] listening on http://127.0.0.1:${PORT}/v1`));
|