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
+73 -14
View File
@@ -1,14 +1,16 @@
/**
* 音频容器识别与 WebM 解码
* 音频容器识别与解码
*
* 小程序在真机上按 `format: 'mp3'` 落盘,但开发者工具用浏览器的 MediaRecorder,
* 产物是 WebM(Matroska)/Opus,文件名却仍是 `.mp3`。若直接按声明格式转给供应商,
* DashScope 会报「DecodePost resample audio from 0 to 16000 failed」。
* 小程序真机按 `format: 'mp3'` 录音,产物是 16k 单声道的 MPEG-2 Layer III;
* 开发者工具用浏览器的 MediaRecorder,产物是 WebM(Matroska)/Opus,文件名却仍是 `.mp3`。
* DashScope 自带的解码器对这两种容器都不可靠(mp3 实测报
* 「DecodePost resample audio from 0 to 16000 failed」),直接透传会整轮失败。
*
* 因此这里按文件头识别真实容器:WebM 先解码成 16bit 单声道 PCM 再走识别,
* 其余格式保持原有链路(供应商直接支持 mp3/aac/wav/pcm)。
* 因此这里按文件头识别真实容器:WebM 与 mp3 都先在服务端解码成 16bit 单声道 PCM
* 再推给供应商,其余格式保持原有链路(供应商直接支持 aac/wav/pcm)。
*/
import decodeWebm, { decoder as createWebmDecoder } from '@audio/decode-webm';
import decodeMp3, { decoder as createMp3Decoder } from '@audio/decode-mp3';
/** WebM / Matroska 的 EBML 魔数:1A 45 DF A3 */
const EBML_MAGIC = 0x1a45dfa3;
@@ -113,6 +115,25 @@ export async function webmToPcm(audio, decodeImpl = decodeWebm) {
return { pcm, rate: Number(result.sampleRate) || 48000, samples: pcm.length / 2 };
}
/**
* MP3 解码为 16bit 单声道 PCM
*
* 真机录音是 16k 单声道 MPEG-2 Layer III,mpg123 能正常解出音频;
* 解码后再按实际采样率(16k 时无需抽取)推给供应商,避开供应商侧的解码失败。
*
* @param {Buffer|Uint8Array} audio - MP3 原始字节
* @param {Function} [decodeImpl] - 测试注入的解码实现
* @returns {Promise<{pcm: Buffer, rate: number, samples: number}>}
*/
export async function mp3ToPcm(audio, decodeImpl = decodeMp3) {
const result = await decodeImpl(audio);
const channelData = Array.isArray(result?.channelData) ? result.channelData : [];
const pcm = channelsToPcm16(channelData);
if (!pcm.length) throw new Error('mp3 decoded audio is empty');
return { pcm, rate: Number(result.sampleRate) || 16000, samples: pcm.length / 2 };
}
/**
* 16bit 单声道 PCM 降采样(整数倍抽取)
*
@@ -143,18 +164,20 @@ export function downsamplePcm16(pcm, fromRate, toRate = 16000) {
}
/**
* 创建 WebM 流式解码器:边收分片边出 16bit 单声道 PCM
* 把容器解码器包成统一的「边收分片边出 16bit 单声道 PCM」接口
*
* 开发者工具的录音是 WebM/Opus,供应商无法直接识别这种容器;
* 整段路径可以等录完再解码,实时链路必须边收边解,才能逐字回填。
* 解码器按 Matroska 结构增量解析,分片边界不必对齐 cluster。
* WebM(Opus) 与 MP3 的增量解码接口一致(decode 返回 channelData/sampleRate),
* 区别只在 WebM 需要 flush 冲尾部、MP3 帧间独立且没有 flush。
*
* @param {Function} [factory] - 测试注入的解码器工厂
* @param {Function} factory - 解码器工厂
* @param {Object} [options]
* @param {number} [options.defaultRate] - 首帧前使用的默认采样率
* @param {boolean} [options.hasFlush] - 是否支持 flush
* @returns {Promise<{rate: number, push: Function, flush: Function, free: Function}>}
*/
export async function createStreamingWebmDecoder(factory = createWebmDecoder) {
async function wrapStreamingDecoder(factory, { defaultRate = 48000, hasFlush = true } = {}) {
const decoder = await factory();
let rate = 48000;
let rate = defaultRate;
const toPcm = (audioData) => {
const sampleRate = Number(audioData?.sampleRate);
@@ -167,13 +190,14 @@ export async function createStreamingWebmDecoder(factory = createWebmDecoder) {
get rate() {
return rate;
},
/** 推入一个 WebM 分片,返回该分片解出的 PCM(可能为空) */
/** 推入一个容器分片,返回该分片解出的 PCM(可能为空) */
async push(chunk) {
// Opus/Vorbis 同步返回,Matroska-only 编码首次加载编码器时是 Promise
return toPcm(await decoder.decode(chunk));
},
/** 收尾,返回剩余 PCM(可能为空) */
async flush() {
if (!hasFlush || typeof decoder.flush !== 'function') return Buffer.alloc(0);
return toPcm(await decoder.flush());
},
free() {
@@ -185,3 +209,38 @@ export async function createStreamingWebmDecoder(factory = createWebmDecoder) {
}
};
}
/**
* 创建 WebM 流式解码器
* @param {Function} [factory] - 测试注入的解码器工厂
* @returns {Promise<{rate: number, push: Function, flush: Function, free: Function}>}
*/
export async function createStreamingWebmDecoder(factory = createWebmDecoder) {
return wrapStreamingDecoder(factory, { defaultRate: 48000, hasFlush: true });
}
/**
* 创建 MP3 流式解码器
* @param {Function} [factory] - 测试注入的解码器工厂
* @returns {Promise<{rate: number, push: Function, flush: Function, free: Function}>}
*/
export async function createStreamingMp3Decoder(factory = createMp3Decoder) {
return wrapStreamingDecoder(factory, { defaultRate: 16000, hasFlush: false });
}
/** 需要服务端解码的容器(其余格式仍直接交给供应商) */
const STREAMING_DECODERS = {
webm: createStreamingWebmDecoder,
mp3: createStreamingMp3Decoder
};
/**
* 按容器创建流式解码器
* @param {'webm'|'mp3'} format - sniffAudioFormat 的结果
* @returns {Promise<{rate: number, push: Function, flush: Function, free: Function}>}
*/
export async function createStreamingAudioDecoder(format) {
const factory = STREAMING_DECODERS[format];
if (!factory) throw new Error(`unsupported streaming audio format: ${format}`);
return factory();
}