HTML5 getUserMedia record webcam, both audio and video

Harm Kabisa picture Harm Kabisa · May 1, 2013 · Viewed 52.9k times · Source

Is it possible to use Chrome to capture video (webcam) and audio (microphone) from the browser and then save the stream as video file?

I would like to use this to create a video/photobooth-like application that allows users to record a simple (30 second) message (both video and audio) to files that can later be watched.

I have read the documentation but I have not (yet) seen any examples on how to capture both audio & video, also I did not find a way yet to store the results in a video file.

Who can help?

Answer

kongaraju picture kongaraju · May 21, 2013

MediaStreamRecorder is a WebRTC API for recording getUserMedia() streams( still under implementation) . It allows web apps to create a file from a live audio/video session.

<script language="javascript" type="text/javascript">
function onVideoFail(e) {
    console.log('webcam fail!', e);
  };

function hasGetUserMedia() {
  // Note: Opera is unprefixed.
  return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia || navigator.msGetUserMedia);
}

if (hasGetUserMedia()) {
  // Good to go!
} else {
  alert('getUserMedia() is not supported in your browser');
}

window.URL = window.URL || window.webkitURL;
navigator.getUserMedia  = navigator.getUserMedia || 
                         navigator.webkitGetUserMedia ||
                          navigator.mozGetUserMedia || 
                           navigator.msGetUserMedia;

var video = document.querySelector('video');
var streamRecorder;
var webcamstream;

if (navigator.getUserMedia) {
  navigator.getUserMedia({audio: true, video: true}, function(stream) {
    video.src = window.URL.createObjectURL(stream);
    webcamstream = stream;
//  streamrecorder = webcamstream.record();
  }, onVideoFail);
} else {
    alert ('failed');
}

function startRecording() {
    streamRecorder = webcamstream.record();
    setTimeout(stopRecording, 10000);
}
function stopRecording() {
    streamRecorder.getRecordedData(postVideoToServer);
}
function postVideoToServer(videoblob) {

    var data = {};
    data.video = videoblob;
    data.metadata = 'test metadata';
    data.action = "upload_video";
    jQuery.post("http://www.foundthru.co.uk/uploadvideo.php", data, onUploadSuccess);
}
function onUploadSuccess() {
    alert ('video uploaded');
}

</script>

<div id="webcamcontrols">
    <button class="recordbutton" onclick="startRecording();">RECORD</button>
</div>

http://www.w3.org/TR/mediastream-recording/