Skip to content

Instantly share code, notes, and snippets.

@pdaug
Last active January 22, 2025 22:27
Show Gist options
  • Select an option

  • Save pdaug/69aa65030aaa5f09858db156d8aeab46 to your computer and use it in GitHub Desktop.

Select an option

Save pdaug/69aa65030aaa5f09858db156d8aeab46 to your computer and use it in GitHub Desktop.
Convert Audio Chunk to Audio PCM and Convert Audio PCM to Audio Base64 Data
/**
* Convert Audio Chunk to Audio PCM 16Bit 24kHz Mono
* (Required audio/wav and 24kHz Mono)
*
* @param {Float32Array<ArrayBufferLike>} chunk
* @returns {Int16Array<ArrayBuffer>}
*/
const chunkToPCM = function (chunk) {
const minimalInt = 0x8000;
const maximalInt = 0x7fff;
const output = new Int16Array(chunk.length);
for (let index = 0; index < chunk.length; index++) {
const currentChunk = chunk[index];
const clamping = Math.max(-1, Math.min(1, currentChunk));
output[index] = clamping < 0 ? clamping * minimalInt : clamping * maximalInt;
}
return output;
};
/**
* Convert Audio PCM to Audio Base64 Data
*
* @param {Int16Array<ArrayBuffer>} pcm
* @returns {string}
*/
const PCMToBase64 = function (pcm) {
let output = "";
const byteArray = new Uint8Array(pcm.buffer);
for (let index = 0; index < byteArray.length; index++) {
const currentByte = byteArray[index];
output += String.fromCharCode(currentByte);
}
return window.btoa(output);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment