Skip to content

Instantly share code, notes, and snippets.

@bertrandg
Forked from also/wave.js
Created May 18, 2017 11:04
Show Gist options
  • Save bertrandg/f0abf0f23f224eba30402fb1795d6142 to your computer and use it in GitHub Desktop.
Save bertrandg/f0abf0f23f224eba30402fb1795d6142 to your computer and use it in GitHub Desktop.
Generate WAVE file headers in JavaScript
// https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
function buildWaveHeader(opts) {
var numFrames = opts.numFrames;
var numChannels = opts.numChannels || 2;
var sampleRate = opts.sampleRate || 44100;
var bytesPerSample = opts.bytesPerSample || 2;
var blockAlign = numChannels * bytesPerSample;
var byteRate = sampleRate * blockAlign;
var dataSize = numFrames * blockAlign;
var buffer = new ArrayBuffer(44);
var dv = new DataView(buffer);
var p = 0;
function writeString(s) {
for (var i = 0; i < s.length; i++) {
dv.setUint8(p + i, s.charCodeAt(i));
}
p += s.length;
}
function writeUint32(d) {
dv.setUint32(p, d, true);
p += 4;
}
function writeUint16(d) {
dv.setUint16(p, d, true);
p += 2;
}
writeString('RIFF'); // ChunkID
writeUint32(dataSize + 36); // ChunkSize
writeString('WAVE'); // Format
writeString('fmt '); // Subchunk1ID
writeUint32(16); // Subchunk1Size
writeUint16(1); // AudioFormat
writeUint16(numChannels); // NumChannels
writeUint32(sampleRate); // SampleRate
writeUint32(byteRate); // ByteRate
writeUint16(blockAlign); // BlockAlign
writeUint16(bytesPerSample * 8); // BitsPerSample
writeString('data'); // Subchunk2ID
writeUint32(dataSize); // Subchunk2Size
return buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment