/ proof-of-concept / audio-spike-sorting
Sign in
proof-of-concept / audio-spike-sorting
audio-spike-sorting / src / export / wav.ts
28 lines · 1.2 KBCodeBlameHistory
2 * Minimal float32 WAV encoder (format tag 3, IEEE float, mono). The
3 * header is exactly 44 bytes with no extra chunks, which the offline
4 * evaluation harness relies on: numbl has no audioread, so tools/load_wav.m
5 * reads the rate at byte 24 and the samples from byte 44. Real MATLAB,
6 * Python soundfile, and audio editors read these files normally.
7 */
8export function wavFloat32(samples: Float32Array, sr: number): Uint8Array {
9 const dataLen = samples.length * 4;
10 const buf = new ArrayBuffer(44 + dataLen);
11 const v = new DataView(buf);
12 const ascii = (off: number, s: string) => { for (let i = 0; i < s.length; i++) v.setUint8(off + i, s.charCodeAt(i)); };
13 ascii(0, 'RIFF');
14 v.setUint32(4, 36 + dataLen, true);
15 ascii(8, 'WAVE');
16 ascii(12, 'fmt ');
17 v.setUint32(16, 16, true); // fmt chunk size
18 v.setUint16(20, 3, true); // IEEE float
19 v.setUint16(22, 1, true); // mono
20 v.setUint32(24, sr, true);
21 v.setUint32(28, sr * 4, true); // byte rate
22 v.setUint16(32, 4, true); // block align
23 v.setUint16(34, 32, true); // bits per sample
24 ascii(36, 'data');
25 v.setUint32(40, dataLen, true);
26 new Float32Array(buf, 44).set(samples);
27 return new Uint8Array(buf);
↑↓ move↵openescclose