Reputation: 333
Hello i'm new to the whole JS + Audio thing. I have a react-mic which records audio from the built in microphone and turns it into a blob after stopping.
For testing i just want to download the built wav file and listen to it.
The wav file is just 15kb every time. So it's empty. The automatic file naming works though.
Any hints on how to turn audio blob to wav?
Thank you!
function onStop(recordedBlob) {
console.log('recordedBlob is: ', recordedBlob);
const fileName = chatId + '-' + Date.now() + '-' + author;
const audioFile = new File([recordedBlob], `${fileName}.wav`, {
type: 'audio/wav',
lastModified: Date.now()
});
const a = document.createElement('a');
a.download = `${fileName}.wav`;
a.href = window.URL.createObjectURL(audioFile);
a.click();
setNewAudioFile(audioFile);
uploadAudio(audioFile);
console.log(audioFile);
}
Upvotes: 0
Views: 5355
Reputation: 413
I have done this by below code:
const reader = new window.FileReader();
reader.readAsDataURL(audioBlob);
reader.onloadend = () => {
let base64 = reader.result + '';
base64 = base64.split(',')[1];
const ab = new ArrayBuffer(base64.length);
const buff = new Buffer.from(base64, 'base64');
const view = new Uint8Array(ab);
for (let i = 0; i < buff.length; ++i) {
view[i] = buff[i];
}
const context = new AudioContext();
context.decodeAudioData(ab, (buffer) => {
const wavFile = toWav(buffer);
const blob = new window.Blob([ new DataView(wavFile) ], {
type: 'audio/wav'
});
const anchor = document.createElement('a');
document.body.appendChild(anchor);
anchor.style = 'display: none';
const url = window.URL.createObjectURL(blob);
anchor.href = url;
anchor.download = 'audio.wav';
anchor.click();
window.URL.revokeObjectURL(url);
}
Upvotes: 1