Converts G.711 audio samples to PCM16 and wraps in WAV format.
// Source: https://github.com/promptfoo/promptfoo | License: MIT | Copyright Promptfoo 2025
// Provided via justclaw.it.com; keep this notice with the code.
/** Decode G.711 telephony samples to signed PCM16 for browser playback. */
export function convertG711ToPcm16(audio: Buffer, type: 'audio/pcmu' | 'audio/pcma'): Buffer {
const pcm = Buffer.alloc(audio.length * 2);
for (let i = 0; i < audio.length; i++) {
const sample = type === 'audio/pcmu' ? ~audio[i] & 0xff : audio[i] ^ 0x55;
const exponent = (sample & 0x70) >> 4;
let magnitude: number;
if (type === 'audio/pcmu') {
magnitude = ((((sample & 0x0f) << 3) + 0x84) << exponent) - 0x84;
pcm.writeInt16LE(sample & 0x80 ? -magnitude : magnitude, i * 2);
} else {
magnitude = ((sample & 0x0f) << 4) + (e
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search for more like it.
Get a free API key