Created
February 25, 2024 19:59
-
-
Save ken107/e765eeb1dd99c7e27c8f0e9fbb33216f to your computer and use it in GitHub Desktop.
Create WAV header for PCM data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function createWavHeader(dataLength: number, sampleRate: number, bitDepth: number, channels: number) { | |
const headerLength = 44; // Standard size of WAV header | |
const totalLength = headerLength + dataLength; | |
const buffer = new ArrayBuffer(headerLength); | |
const view = new DataView(buffer); | |
// RIFF chunk descriptor | |
writeString(view, 0, 'RIFF'); // ChunkID | |
view.setUint32(4, totalLength - 8, true); // ChunkSize (file size - 8 bytes) | |
writeString(view, 8, 'WAVE'); // Format | |
// fmt subchunk (format details) | |
writeString(view, 12, 'fmt '); // Subchunk1ID | |
view.setUint32(16, 16, true); // Subchunk1Size (16 for PCM) | |
view.setUint16(20, 1, true); // AudioFormat (1 for PCM) | |
view.setUint16(22, channels, true); // NumChannels | |
view.setUint32(24, sampleRate, true); // SampleRate | |
view.setUint32(28, sampleRate * channels * bitDepth / 8, true); // ByteRate | |
view.setUint16(32, channels * bitDepth / 8, true); // BlockAlign | |
view.setUint16(34, bitDepth, true); // BitsPerSample | |
// data subchunk (actual sound data) | |
writeString(view, 36, 'data'); // Subchunk2ID | |
view.setUint32(40, dataLength, true); // Subchunk2Size | |
return buffer; | |
function writeString(view: DataView, offset: number, string: string) { | |
for (let i = 0; i < string.length; i++) { | |
view.setUint8(offset + i, string.charCodeAt(i)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment