UNPKG

@lobehub/tts

Version:

A high-quality & reliable TTS React Hooks library

50 lines (49 loc) 1.43 kB
//#region src/core/utils/audioBufferToBlob.ts const audioBufferToWav = async (buffer) => { const numOfChan = buffer.numberOfChannels; const length = buffer.length * numOfChan * 2 + 44; const bufferOut = new ArrayBuffer(length); const view = new DataView(bufferOut); const channels = []; let sample; let offset = 0; let pos = 0; const setUint16 = (data) => { view.setUint16(pos, data, true); pos += 2; }; const setUint32 = (data) => { view.setUint32(pos, data, true); pos += 4; }; setUint32(1179011410); setUint32(length - 8); setUint32(1163280727); setUint32(544501094); setUint32(16); setUint16(1); setUint16(numOfChan); setUint32(buffer.sampleRate); setUint32(buffer.sampleRate * 2 * numOfChan); setUint16(numOfChan * 2); setUint16(16); setUint32(1635017060); setUint32(length - pos - 4); for (let i = 0; i < buffer.numberOfChannels; i++) channels.push(buffer.getChannelData(i)); while (offset < buffer.length) { for (let i = 0; i < numOfChan; i++) { sample = Math.max(-1, Math.min(1, channels[i][offset])); sample = Math.trunc(.5 + sample < 0 ? sample * 32768 : sample * 32767); view.setInt16(pos, sample, true); pos += 2; } offset++; } return bufferOut; }; const audioBufferToBlob = async (audioBuffer) => { const wavArrayBuffer = await audioBufferToWav(audioBuffer); return new Blob([wavArrayBuffer], { type: "audio/wav" }); }; //#endregion export { audioBufferToBlob };