Monday, January 23, 2012

How to access the webcam using HTML5 getUserMedia

HTML5 getUserMedia helps in  accessing the camera or microphone through browsers without the use of plugins.

Following tutorial helps you in creating an HTML page, that access the camera without the use of plugins.

Before getting started, make sure to install Google Chrome or Opera  or Firefox nightly build and make sure your webcam is working properly ;)

Enabling HTML5 getUserMedia support:

HTML5 getUserMedia is enabled by default in Opera.  For Google Chrome, you need to enable it manually.  Type 'chrome://flags' in your address bar.  Find 'Enable MediaStream'.

Enable HTML5 getUserMedia support in Google Chrome
Enable HTML5 getUserMedia support in Google Chrome
Enable it and restart your browser.

HTML5 getUserMedia:

To access webcam from browser without the use of plugins, you need to know getUserMedia method in detail.

getUserMedia method takes 3 arguments.  First argument specifies which type of device we are about to access.  If it is microphone you  need to specify ‘{audio:true}’, if it is webcam then it is '{video:true}’.  In this tutorial we will see only the video part.

The second and third arguments are used for call back.


  getUserMedia (media name(video or audio),success callback,failure callback)

You can create two functions stating what should happen when user acknowledges your request (a success function) and when user rejects your request(a failure function).   You can now pass the success function to the second argument and the failure function to the third argument.

When user accepts the request, success function is called as a callback function along with  the stream.  When user rejects your request, failure function is called  along with the error detail.  Failure callback is optional, though it is helpful.  Though Chrome and Opera allows you to define callback methods elsewhere and call it in getUserMedia call, Firefox expects you to define the callback methods right in the method call.

Pass the stream  to the source of the video element and play it.  Your webcam starts now.  Make sure to allow your browser to access webcam

Navigator Object:

In this tutorial, we will make use of JavaScript Navigator object to access information about the browser you are using.


CreateObjectURL is used to create new object URL, which is tied to the document in the window on which it was created.  In this tutorial, we will use it to create object url using the stream and assigning it to the source of the video. Since Webkit browsers like Google Chrome, adds prefix to the url (WebkitURL), we need a extra step to make sure our code to support all browsers.

window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; 

The above code returns webkitURL for Chrome, mozURL for Firefox and more.

For Firefox, you can pass the stream to the video source, without using CreateObjectURL.

Feature Detection:

Since HTML5 is relatively young, not all the browser supports getUserMedia.  So you need to handle things when a browser doesn't support it.  You can do this by browser detection, which is the oldest method, but I prefer feature detection.  Here is why.  You can detect whether the browser supports getUserMedia() method by calling this line

if (navigator.getUserMedia) 

This returns true, when the browser supports it else it returns false.  You can handle things accordingly.

HTML code

<!DOCTYPE html> 
<html lang="en">
    <title>HTML5 Exploding Camera Demo</title> 
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=yes">

    <div role="main">

        <video id="sourcevid" autoplay>Sorry, you're browser doesn't support video. Please try <a href="">Opera</a>.</video>
        <input type="button" value="Start" onclick="start()" >
        <input type="button" value="Stop" onclick="stop()" >
    <script src="camera.js"></script>

JavaScript code

var video;

function start() {
    video = document.getElementById('sourcevid');
 // Get the stream from the camera using getUserMedia
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
    window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
    if (navigator.getUserMedia) {
        // This beautiful hack for the options is from @kanasansoft:
        var gumOptions = {video: true, toString: function(){return 'video';}};
        function successCallback(stream) {
            // Replace the source of the video element with the stream from the camera
         if(navigator.getUserMedia==navigator.mozGetUserMedia) {
          video.src = stream;
         } else {
          video.src = window.URL.createObjectURL(stream) || stream;
        function errorCallback(error) {
            console.error('An error occurred: [CODE ' + error.code + ']');
    } else {
        var errorMsg = '<p class="error">Uh oh, it appears your browser doesn\'t support this feature.<br>Please try with a <a href="">browser that has camera support</a>.</p>';
        document.querySelector('[role=main]').innerHTML = errorMsg;
        console.log('Native web camera streaming (getUserMedia) is not supported in this browser.');;

function stop()
 video = document.getElementById('sourcevid');
 video.src = "";

This example is derived from  explode camera demo. Explode camera demo works fine with Opera and Chrome and not Firefox.

For Further Reading:
  1. Capturing audio & video in HTML5 - HTML5 Rocks.
  2. Playing with HTML5 video & getUserMedia support - Opera
Share your opinions through comments

  © Blogger templates Newspaper III by 2008

Back to TOP