Skip to content

bmson/ArraybufferToWav

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

ArraybufferToWav

Encodes a standard 44-byte RIFF/WAVE header (PCM, 16-bit, mono) followed by the sample data, per RFC 2361.

Usage

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);

Parameters

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.

Play in the browser

const blob = arrayBufferToWav(samples);
const audio = new Audio(URL.createObjectURL(blob));
audio.play();

Download as a file

const blob = arrayBufferToWav(samples);
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'recording.wav';
a.click();

With the Web Audio API

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);

Exports

default - arrayBufferToWav(data, sampleRate?)

Encodes audio samples into a WAV Blob.

clamp(input, { min, max })

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

How it works

  1. Allocates an ArrayBuffer - 44 bytes for the RIFF/WAVE header + 2 bytes per sample (16-bit).
  2. Writes the header fields (RIFF, WAVE, fmt , data) via DataView.
  3. Converts each float sample to a signed 16-bit integer, clamping to [-1, 1] first.
  4. Returns the buffer wrapped in a Blob.

Limitations

  • Mono only - NumChannels is hardcoded to 1. For stereo, interleave channels before passing them in.
  • 16-bit PCM only - no support for 8-bit, 24-bit, or floating-point WAV formats.

About

Convert ArrayBuffer to Waveform Audio file

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors