How to Record video use getUserMedia and MediaRecorder API

example

sample codes

  <div>
    <video id='camera'></video>
  </div>
  <script type='text/javascript'>
    var p = navigator.mediaDevices.getUserMedia({ audio: true, video: true });
    p.then(function(mediaStream) {
      var video = document.querySelector('video');
      video.src = window.URL.createObjectURL(mediaStream);
      video.onloadedmetadata = function() {
        video.muted = true;
        video.play();
      }
      var mediaRecorder = new MediaRecorder(mediaStream);
      var chunks = [];
      mediaRecorder.ondataavailable = function(e) {
        chunks.push(e.data);
      }
      mediaRecorder.onstop = function() {
        var blob = new Blob(chunks, {'type' : 'video/webm'});
        chunks = [];
        var hyperlink = document.createElement('a');
        hyperlink.href = URL.createObjectURL(blob);
        video.src = hyperlink.href;
        video.muted = false;
        video.controls = true;
        hyperlink.download = 'record.mp4';
        hyperlink.style = 'display:none;opacity:0;color:transparent;';
        (document.body || document.documentElement).appendChild(hyperlink);
if (typeof hyperlink.click === 'function') {
  hyperlink.click();
} else {
            hyperlink.target = '_blank';
            hyperlink.dispatchEvent(new MouseEvent('click', {
                view: window,
                bubbles: true,
                cancelable: true
            }));
        }     
    }
      mediaRecorder.start();      
      setTimeout(function() {
        mediaRecorder.stop();
        video.src = '';
        video.muted = false;
        video.stop();
      }, 10000);
    });
</script>

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe