Encodes a standard 44-byte RIFF/WAVE header (PCM, 16-bit, mono) followed by the sample data, per RFC 2361.
import arrayBufferToWav from './lib.js';
// Float32Array of audio samples in the range [-1, 1]
const samples = new Float32Array([0, 0.5, 1, 0.5, 0, -0.5, -1, -0.5]);
const blob = arrayBufferToWav(samples, 44100);| Parameter | Type | Default | Description |
|---|---|---|---|
data |
Float32Array |
- | Audio samples, expected in the range [-1, 1]. Values outside this range are clamped. |
sampleRate |
number |
44100 |
Sample rate in Hz (e.g. 8000, 16000, 44100, 48000). |
Returns a Blob with MIME type audio/wav.
const blob = arrayBufferToWav(samples);
const audio = new Audio(URL.createObjectURL(blob));
audio.play();const blob = arrayBufferToWav(samples);
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'recording.wav';
a.click();const ctx = new AudioContext();
const source = ctx.createBufferSource();
source.buffer = audioBuffer;
// Extract channel data and encode
const samples = audioBuffer.getChannelData(0);
const blob = arrayBufferToWav(samples, audioBuffer.sampleRate);Encodes audio samples into a WAV Blob.
Utility that clamps a number to a given range.
import { clamp } from './lib.js';
clamp(1.5, { min: -1, max: 1 }); // 1
clamp(-2, { min: -1, max: 1 }); // -1- Allocates an
ArrayBuffer- 44 bytes for the RIFF/WAVE header + 2 bytes per sample (16-bit). - Writes the header fields (
RIFF,WAVE,fmt,data) viaDataView. - Converts each float sample to a signed 16-bit integer, clamping to
[-1, 1]first. - Returns the buffer wrapped in a
Blob.
- Mono only -
NumChannelsis hardcoded to1. For stereo, interleave channels before passing them in. - 16-bit PCM only - no support for 8-bit, 24-bit, or floating-point WAV formats.