fix: 真机 16k mp3 服务端解码为 PCM,修复 ASR 实时回显失败

DashScope 无法解码微信真机录制的 16k MPEG-2 Layer III mp3(报 DecodePost resample audio from 0 to 16000 failed)。按文件头识别容器后,实时与整段两条链路统一先解码为 16bit 单声道 PCM 再推供应商。
This commit is contained in:
lik
2026-10-31 19:54:37 +08:00
parent 02d57f82dc
commit 13981c047b
7 changed files with 186 additions and 63 deletions
+60
View File
@@ -16,9 +16,12 @@ import {
MediaInputError,
} from "../agent/infra/media/index.js";
import {
createStreamingAudioDecoder,
createStreamingMp3Decoder,
createStreamingWebmDecoder,
downsamplePcm16,
findEbmlHeader,
mp3ToPcm,
sniffAudioFormat,
webmToPcm,
} from "../agent/infra/media/audio.js";
@@ -120,6 +123,63 @@ test("WebM 流式解码器按分片连续产出 PCM", async () => {
decoder.free();
});
test("MP3 解码结果下混为 16bit 单声道 PCM", async () => {
// mpg123 对单声道也输出左右两路相同的通道数据,下混后仍是原样本
const { pcm, rate, samples } = await mp3ToPcm(Buffer.from("mp3"), async () => ({
channelData: [
new Float32Array([0.5, -0.5]),
new Float32Array([0.5, -0.5]),
],
sampleRate: 16000,
}));
assert.equal(rate, 16000);
assert.equal(samples, 2);
assert.equal(pcm.length, 4);
assert.equal(pcm.readInt16LE(0), Math.round(0.5 * 32767));
assert.equal(pcm.readInt16LE(2), Math.round(-0.5 * 32767));
await assert.rejects(
() => mp3ToPcm(Buffer.from("mp3"), async () => ({ channelData: [] })),
/decoded audio is empty/
);
});
test("MP3 流式解码器按分片产出 PCM,并以解码器实际采样率为准", async () => {
const fakeDecoder = {
decode(chunk) {
// 不足一帧时 mpg123 返回空通道数据和 0 采样率,不能把 rate 写成 0
if (chunk.length < 4) return { channelData: [], sampleRate: 0 };
return {
channelData: [new Float32Array([0.5]), new Float32Array([0.5])],
sampleRate: 16000,
};
},
free() {},
};
const decoder = await createStreamingMp3Decoder(async () => fakeDecoder);
assert.equal(decoder.rate, 16000);
assert.equal((await decoder.push(Buffer.from([1, 2, 3]))).length, 0);
assert.equal(decoder.rate, 16000);
const pcm = await decoder.push(Buffer.from([4, 5, 6, 7]));
assert.equal(pcm.length, 2);
assert.equal(pcm.readInt16LE(0), Math.round(0.5 * 32767));
// mp3 没有尾部缓冲,flush 必须是空结果而不是抛错
assert.equal((await decoder.flush()).length, 0);
decoder.free();
});
test("流式解码器按容器分发,未知容器直接报错", async () => {
// 只验证分发入口的契约,避免在单测里加载 WASM 解码器
await assert.rejects(
() => createStreamingAudioDecoder("aac"),
/unsupported streaming audio format/
);
});
test("48k PCM 按整数倍抽取到 16k,非整数倍保持原样", () => {
const pcm = Buffer.alloc(48 * 2);
for (let i = 0; i < 48; i += 1) {