Discuss Scratch

TerrariaMods
Scratcher
100+ posts

Recording Microphone HTML5

How can I record audio in an HTML5 webpage using MediaRecorder()?
Chiroyce
Scratcher
1000+ posts

Recording Microphone HTML5

I did this once and oh boy did it take a while to properly understand this API

const audio = document.querySelector('audio'); // There should be at least ONE <audio> element in your HTML
const button = document.querySelector('button'); // Used to stop the recording

navigator.mediaDevices.getUserMedia({video: false, audio: true})
.then((stream) => {
let chunks = []
let mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start()

button.onclick = () => {
mediaRecorder.stop();
}

mediaRecorder.onstop = (e) => {
myBlob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
audio.src = URL.createObjectURL(myBlob); // The audio's blob will be converted to a url
// And the audio's source will be the recorded blob
audio.play();
}

mediaRecorder.ondataavailable = (e) => {
chunks.push(e.data);
}
})

The main issue I faced was having to deal with how mediaRecorder.ondataavailable only triggered when the audio finished recording

Last edited by Chiroyce (March 17, 2022 04:24:12)

TerrariaMods
Scratcher
100+ posts

Recording Microphone HTML5

@Chiroyce Thanks! My issue was trying to find where to get the stream to feed into the MediaRecorder.
Chiroyce
Scratcher
1000+ posts

Recording Microphone HTML5

TerrariaMods wrote:

@Chiroyce Thanks! My issue was trying to find where to get the stream to feed into the MediaRecorder.
MDN is the best! — https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder
TerrariaMods
Scratcher
100+ posts

Recording Microphone HTML5

@Chiroyce Do you happen to know any alternatives to MediaRecorder? The quality of a recorded canvas element isn't very high, and I would like to fix that.
Chiroyce
Scratcher
1000+ posts

Recording Microphone HTML5

TerrariaMods wrote:

Do you happen to know any alternatives to MediaRecorder? The quality of a recorded canvas element isn't very high, and I would like to fix that.
Try increasing the bitrate maybe? https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/MediaRecorder

Powered by DjangoBB