1// Minimal 16-bit PCM WAV writer.
2export function encodeWav(y, sampleRate) {
3 const n = y.length;
4 const buf = new ArrayBuffer(44 + 2 * n);
5 const dv = new DataView(buf);
6 const wstr = (o, s) => { for (let i = 0; i < s.length; i++) dv.setUint8(o + i, s.charCodeAt(i)); };
7 wstr(0, 'RIFF'); dv.setUint32(4, 36 + 2 * n, true); wstr(8, 'WAVE');
8 wstr(12, 'fmt '); dv.setUint32(16, 16, true);
9 dv.setUint16(20, 1, true); dv.setUint16(22, 1, true);
10 dv.setUint32(24, sampleRate, true); dv.setUint32(28, sampleRate * 2, true);
11 dv.setUint16(32, 2, true); dv.setUint16(34, 16, true);
12 wstr(36, 'data'); dv.setUint32(40, 2 * n, true);
13 for (let i = 0; i < n; i++) {
14 const v = Math.max(-1, Math.min(1, y[i]));
15 dv.setInt16(44 + 2 * i, Math.round(v * 32767), true);
16 }
17 return Buffer.from(buf);
18}