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