v135 · javascript
Audio sample compression
Audio PCM samples are normally stored as 32-bit floats, but for large buffers (streaming, ML preprocessing, network transfer) the precision loss from converting to 16-bit float is inaudible. Float16Array holds the compressed samples natively without a manual bit-packing step.
Feature detection: checking…
PCM sample comparison — Float32 vs Float16
440 Hz sine
Signal:
Float32 (original) — 4 bytes/sample
Float16 (compressed) — 2 bytes/sample
Float32 buffer size
—
Float16 buffer size
—
Compression ratio
2×
Max sample error
—
Mean abs error
—
SNR (estimated)
—
First 10 samples:
| index | Float32 | → Float16 | error | relative err |
|---|
Error distribution — how many samples fall in each precision bucket
// 1 second of audio at 44100 Hz
const sampleRate = 44100;
const f32 = new Float32Array(sampleRate);
// Fill with 440 Hz sine wave
for (let i = 0; i < sampleRate; i++) {
f32[i] = Math.sin(2 * Math.PI * 440 * i / sampleRate);
}
// Convert to Float16 — half the bytes, near-identical waveform
const f16 = new Float16Array(f32.length);
for (let i = 0; i < f32.length; i++) {
f16[i] = f32[i]; // engine converts 32→16 bit float
}
// f32.byteLength = 176400 bytes
// f16.byteLength = 88200 bytes ← 2× smaller
// max error per sample ≈ 0.0005 ← inaudible