Created
November 30, 2021 21:36
-
-
Save sayjeyhi/444373df08222485617e2135f453c64d to your computer and use it in GitHub Desktop.
This file contains 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 const concatArrayBuffers = (buffer1: ArrayBuffer, buffer2: Buffer) => { | |
const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength); | |
tmp.set(new Uint8Array(buffer1), 0); | |
tmp.set(new Uint8Array(buffer2), buffer1.byteLength); | |
return tmp.buffer; | |
}; | |
export const withWaveHeader = (data: Buffer, numberOfChannels: number, sampleRate: number) => { | |
const header = new ArrayBuffer(44); | |
const view = new DataView(header); | |
let pos = 0; | |
function setUint16(data: any) { | |
view.setUint16(pos, data, true); | |
pos += 2; | |
} | |
function setUint32(data: any) { | |
view.setUint32(pos, data, true); | |
pos += 4; | |
} | |
// write WAVE header | |
setUint32(0x46464952); // "RIFF" | |
setUint32(length - 8); // file length - 8 | |
setUint32(0x45564157); // "WAVE" | |
setUint32(0x20746d66); // "fmt " chunk | |
setUint32(16); // length = 16 | |
setUint16(1); // PCM (uncompressed) | |
setUint16(numberOfChannels); | |
setUint32(sampleRate); | |
setUint32(sampleRate * 2 * numberOfChannels); // avg. bytes/sec | |
setUint16(numberOfChannels * 2); // block-align | |
setUint16(16); // 16-bit (hardcoded in this demo) | |
setUint32(0x61746164); // "data" - chunk | |
setUint32(length - pos - 4); // chunk length | |
return concatArrayBuffers(header, data); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment