JSFiddle - React, Tailwind, and code Playground
by Guang-De Lin
HTML
<video id="cam" muted></video> <br>
<button id="download" disabled>Download</button>
CSS
video {
background: #000;
width: 50%;
}
button {
font-size: 2em;
}
JavaScript
var video = document.getElementById('cam');
var button = document.getElementById('download');
function download(filename, data) {
var link = document.createElement('a');
link.setAttribute('href', window.URL.createObjectURL(data));
link.setAttribute('download', filename);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(function (stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
var recorder = new MediaRecorder(stream, { mimeType: 'video/webm' });
video.addEventListener('loadeddata', function () {
recorder.start();
button.disabled = false;
setTimeout(fnStopRecording, 20000);
});
var fnStopRecording = function() {
if ('recording' === recorder.state) {
recorder.stop();
}
};
button.addEventListener('click', fnStopRecording);
recorder.addEventListener('dataavailable', function (evt) {
download('video.webm', evt.data);
});
});