/ proof-of-concept / instrawave-compose
Sign in
proof-of-concept / instrawave-compose
instrawave-compose / src / render / wav.ts
29 lines · 1.0 KBCodeBlameHistory
838af43Per-instrument render cache in IndexedDB and .wav downloadJeremy Magland 1/** A mono float trace as 16-bit PCM .wav bytes, clipped to [-1, 1]. The
2 * mix is already levelled and at the mix rate, so no resampling or
3 * normalization happens here. */
4export function wavBytes(samples: Float32Array, sr: number): Uint8Array {
5 const n = samples.length;
6 const buf = new ArrayBuffer(44 + 2 * n);
7 const view = new DataView(buf);
8 const str = (off: number, s: string): void => {
9 for (let i = 0; i < s.length; i++) view.setUint8(off + i, s.charCodeAt(i));
10 };
11 str(0, 'RIFF');
12 view.setUint32(4, 36 + 2 * n, true);
13 str(8, 'WAVE');
14 str(12, 'fmt ');
15 view.setUint32(16, 16, true);
16 view.setUint16(20, 1, true); // PCM
17 view.setUint16(22, 1, true); // mono
18 view.setUint32(24, sr, true);
19 view.setUint32(28, 2 * sr, true);
20 view.setUint16(32, 2, true);
21 view.setUint16(34, 16, true);
22 str(36, 'data');
23 view.setUint32(40, 2 * n, true);
24 for (let i = 0; i < n; i++) {
25 const v = Math.max(-1, Math.min(1, samples[i]));
26 view.setInt16(44 + 2 * i, Math.round(v * 32767), true);
27 }
28 return new Uint8Array(buf);
↑↓ move↵openescclose