Files
api_health/agent/infra/media/audio.js
T
lik 8c6feaf42d feat: 新增语音/图像识别能力(媒体会话、识别接口与路由)
识别只返回文本,不投递、不落库:语音支持 mp3/aac/wav/pcm,WebM 先按文件头识别再转 PCM;图片走 qwen-vl-ocr。新增 /health/ai/asr 与 /health/ai/ocr,登录后按用户限流 20 次/分钟,并对 /health/ai/ 前缀放宽请求体上限。
2026-10-31 17:02:42 +08:00

168 lines
5.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 音频容器识别与 WebM 解码
*
* 小程序在真机上按 `format: 'mp3'` 落盘,但开发者工具用浏览器的 MediaRecorder,
* 产物是 WebM(Matroska)/Opus,文件名却仍是 `.mp3`。若直接按声明格式转给供应商,
* DashScope 会报「DecodePost resample audio from 0 to 16000 failed」。
*
* 因此这里按文件头识别真实容器:WebM 先解码成 16bit 单声道 PCM 再走识别,
* 其余格式保持原有链路(供应商直接支持 mp3/aac/wav/pcm)。
*/
import decodeWebm, { decoder as createWebmDecoder } from '@audio/decode-webm';
/** WebM / Matroska 的 EBML 魔数:1A 45 DF A3 */
const EBML_MAGIC = 0x1a45dfa3;
/**
* 按文件头判断音频容器
* @param {Buffer|Uint8Array} audio - 原始音频字节
* @returns {'webm'|'wav'|'mp3'|'aac'|'amr'|'ogg'|'unknown'}
*/
export function sniffAudioFormat(audio) {
if (!audio || audio.length < 2) return 'unknown';
const head = Buffer.isBuffer(audio) ? audio : Buffer.from(audio);
if (head.length >= 4 && head.readUInt32BE(0) === EBML_MAGIC) return 'webm';
// RIFF....WAVE
if (
head.length >= 12 &&
head.toString('ascii', 0, 4) === 'RIFF' &&
head.toString('ascii', 8, 12) === 'WAVE'
) {
return 'wav';
}
if (head.length >= 3 && head.toString('ascii', 0, 3) === 'ID3') return 'mp3';
if (head.length >= 4 && head.toString('ascii', 0, 4) === 'OggS') return 'ogg';
if (head.length >= 5 && head.toString('ascii', 0, 5) === '#!AMR') return 'amr';
// 0xFF 同步字:layer 位为 00 是 ADTS AAC,其余是 MPEG 音频(mp3)
if ((head[0] & 0xff) === 0xff && (head[1] & 0xe0) === 0xe0) {
const layer = (head[1] >> 1) & 0x03;
return layer === 0 ? 'aac' : 'mp3';
}
return 'unknown';
}
/**
* Float32 声道数据 → 16bit 单声道 PCM
*
* 多声道取平均下混;浮点越界(解码瑕疵)裁到 [-1, 1],
* 否则 writeInt16LE 会回绕成爆音。整段与流式解码共用这一份实现。
*
* @param {Float32Array[]} channelData
* @returns {Buffer}
*/
export function channelsToPcm16(channelData) {
const channels = Array.isArray(channelData) ? channelData.length : 0;
const samples = channels && channelData[0] ? channelData[0].length : 0;
if (!samples) return Buffer.alloc(0);
const pcm = Buffer.allocUnsafe(samples * 2);
for (let i = 0; i < samples; i += 1) {
let sample = 0;
for (let c = 0; c < channels; c += 1) {
sample += channelData[c][i] || 0;
}
sample /= channels;
const clamped = sample > 1 ? 1 : sample < -1 ? -1 : sample;
pcm.writeInt16LE(Math.round(clamped * 32767), i * 2);
}
return pcm;
}
/**
* WebM/Opus 解码为 16bit 单声道 PCM
*
* 解码器输出 Float32,多声道时取平均下混;Opus 固定输出 48kHz,
* 属于实时识别协议支持的采样率(8k/16k/24k/48k)。
*
* @param {Buffer|Uint8Array} audio - WebM 原始字节
* @param {Function} [decodeImpl] - 测试注入的解码实现
* @returns {Promise<{pcm: Buffer, rate: number, samples: number}>}
*/
export async function webmToPcm(audio, decodeImpl = decodeWebm) {
const result = await decodeImpl(audio);
const channelData = Array.isArray(result?.channelData) ? result.channelData : [];
const pcm = channelsToPcm16(channelData);
if (!pcm.length) throw new Error('webm decoded audio is empty');
return { pcm, rate: Number(result.sampleRate) || 48000, samples: pcm.length / 2 };
}
/**
* 16bit 单声道 PCM 降采样(整数倍抽取)
*
* WebM/Opus 解码出来是 48kHz,而实时识别供应商对裸 PCM 只稳定支持 16k:
* 48k 原生推流既翻倍带宽,也容易被参数校验拒掉。48k→16k 每 3 个点取均值,
* 兼作简易低通,避免直接抽取产生混叠。不适用的采样率原样返回。
*
* @param {Buffer} pcm - 16bit 单声道 PCM
* @param {number} fromRate - 源采样率
* @param {number} [toRate] - 目标采样率
* @returns {Buffer}
*/
export function downsamplePcm16(pcm, fromRate, toRate = 16000) {
const factor = Number(fromRate) / Number(toRate);
if (!Number.isInteger(factor) || factor < 2) return pcm;
const frames = Math.floor(pcm.length / 2 / factor);
const out = Buffer.allocUnsafe(frames * 2);
for (let i = 0; i < frames; i += 1) {
let sum = 0;
for (let j = 0; j < factor; j += 1) {
sum += pcm.readInt16LE((i * factor + j) * 2);
}
const value = Math.round(sum / factor);
out.writeInt16LE(value > 32767 ? 32767 : value < -32768 ? -32768 : value, i * 2);
}
return out;
}
/**
* 创建 WebM 流式解码器:边收分片边出 16bit 单声道 PCM
*
* 开发者工具的录音是 WebM/Opus,供应商无法直接识别这种容器;
* 整段路径可以等录完再解码,实时链路必须边收边解,才能逐字回填。
* 解码器按 Matroska 结构增量解析,分片边界不必对齐 cluster。
*
* @param {Function} [factory] - 测试注入的解码器工厂
* @returns {Promise<{rate: number, push: Function, flush: Function, free: Function}>}
*/
export async function createStreamingWebmDecoder(factory = createWebmDecoder) {
const decoder = await factory();
let rate = 48000;
const toPcm = (audioData) => {
const sampleRate = Number(audioData?.sampleRate);
if (sampleRate > 0) rate = sampleRate;
const channelData = Array.isArray(audioData?.channelData) ? audioData.channelData : [];
return channelsToPcm16(channelData);
};
return {
get rate() {
return rate;
},
/** 推入一个 WebM 分片,返回该分片解出的 PCM(可能为空) */
async push(chunk) {
// Opus/Vorbis 同步返回,Matroska-only 编码首次加载编码器时是 Promise
return toPcm(await decoder.decode(chunk));
},
/** 收尾,返回剩余 PCM(可能为空) */
async flush() {
return toPcm(await decoder.flush());
},
free() {
try {
decoder.free?.();
} catch {
// 释放失败不影响本轮结果
}
}
};
}