JSFiddle - React, Tailwind, and code Playground
HTML
<button id="recButton">
Record
</button><br>
<canvas id="canvas"></canvas>
JavaScript
// we need to initialize a context from our <canvas>
canvas.getContext("2d");
let recording = false;
let mediaRecorder;
const chunks = [];
let newStream, canvasStream
const constrains = {
audio: {
channelCount: { ideal: 2, min: 1 },
sampleRate: 48000,
sampleSize: 16,
volume: 1,
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
},
video: false
};
recButton.addEventListener("click", () => {
recording = !recording;
if (recording) {
recButton.textContent = "Click to Stop";
recButton.style.color = "red";
canvasStream = canvas.captureStream(40);
// force activate the Canvas track
forceEmptyDrawing(canvas);
navigator.mediaDevices.getUserMedia(constrains) // ---> audioStream
.then(audioStream => {
canvasStream.addTrack(audioStream.getTracks()[0]); // --> joint the two streams
mediaRecorder = new MediaRecorder(canvasStream, {
// don't forget the audio codec
mimeType: "video/webm; codecs=vp9,opus",
// ignoreMutedMedia: false
});
mediaRecorder.ondataavailable = e => {
if (e.data.size > 0) {
chunks.push(e.data);
}
};
mediaRecorder.start(10);
})
.catch(err => {
console.log(err.name, err.message);
});
} else {
recButton.textContent = "Record";
recButton.style.color = "black";
mediaRecorder.stop()
// wait for the stop event
// don't rely on some magic timeout
mediaRecorder.onstop = () => {
// only when the recorder is completely stopped
// you can stop the tracks
stopTracks(canvasStream);
const blob = new Blob(chunks, {
type: "video/webm" // you asked for webm, not mp4
});
// just to verify we did record something
console.log(`recorded a ${ blob.size }b file`);
};
}
});
const stopTracks = stream => stream.getTracks().forEach(track => track.stop());
// draws a 1x1...