// 16-bit mono PCM WAV, normalized to the given peak (default -1 dBFS). export function encodeWav(x: Float32Array, fs: number, peak = 0.89): Blob { let m = 0; for (let i = 0; i < x.length; i++) m = Math.max(m, Math.abs(x[i])); const g = m > 0 ? peak / m : 0; const buf = new ArrayBuffer(44 + 2 * x.length); const v = new DataView(buf); const str = (o: number, s: string) => { for (let i = 0; i < s.length; i++) v.setUint8(o + i, s.charCodeAt(i)); }; str(0, 'RIFF'); v.setUint32(4, 36 + 2 * x.length, true); str(8, 'WAVE'); str(12, 'fmt '); v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true); v.setUint32(24, fs, true); v.setUint32(28, fs * 2, true); v.setUint16(32, 2, true); v.setUint16(34, 16, true); str(36, 'data'); v.setUint32(40, 2 * x.length, true); for (let i = 0; i < x.length; i++) { const s = Math.max(-1, Math.min(1, x[i] * g)); v.setInt16(44 + 2 * i, Math.round(s * 32767), true); } return new Blob([buf], { type: 'audio/wav' }); }