To record audio to file with HTML5 and JavaScript, we call the getUserMedia
method.
For instance, we write
const audio = document.getElementById("audio_preview");
const onRecordFail = (e) => {
console.log(e);
};
navigator.getUserMedia(
{ video: false, audio: true },
(stream) => {
audio.src = window.URL.createObjectURL(stream);
},
onRecordFail
);
to select the audio element with getElementById
.
Then we call navigator.getUserMedia
with { video: false, audio: true }
to let us record audio.
We call it with a callback that gets the captured data from stream
and create a base64 URL from it with createObjectURL
.
We set it as the src
property value to play in the audio element.
onRecordFail
is called when capturing fails.