Getting started with getUserMedia

Last month, Opera gave us a preview of their work on the getUserMedia method which allows users to interact with HTML5 applications via webcam and microphone. Now that Chrome has also started to support this feature on its development channel build (Chrome Canary), we can hope to reach a wider audience that can use this technology in the future.

To start, you will first need an install of Opera Labs or Chrome Canary (with MediaStream enabled). Update: The latest versions of Opera and Chrome now support this feature! Got it? Good. On with the code!

var n = navigator,
    is_webkit = false;
 
function onSuccess(stream) {
    var output = document.getElementById('output'), // a video element
    source;
 
    output.autoplay = true; // you can set this in your markup instead
 
    if (!is_webkit) {
        source = stream;
    }
    else {
        source = window.webkitURL.createObjectURL(stream);
    }
 
    output.src = source;
}
 
function onError() {
    // womp, womp =(
}
 
if (n.getUserMedia) {
    // opera users (hopefully everyone else at some point)
    n.getUserMedia({video: true, audio: true}, onSuccess, onError);
}
else if (n.webkitGetUserMedia) {
    // webkit users
    is_webkit = true;
    n.webkitGetUserMedia('video, audio', onSuccess, onError);
}
else {
    // moms, dads, grandmas, and grandpas
}

At the time of this writing, this method is not fully standardized. As a result, Opera and Webkit differ slightly. We create a flag, is_webkit, to check which browser we are in and handle these differences accordingly. We start by checking for support with what will (hopefully) become the standard method—getUserMedia, which is a property of the Navigator object:

if (n.getUserMedia) {
    // opera users (hopefully everyone else at some point)
    n.getUserMedia({video: true, audio: true}, onSuccess, onError);
}
else if (n.webkitGetUserMedia) {
    // webkit users
    is_webkit = true;
    n.webkitGetUserMedia('video, audio', onSuccess, onError);
}

The first parameter states which type of media we want access to. Opera takes an object, while WebKit, relying upon an older version of the spec, accepts a comma-delimited string. Update (May 17, 2012): Canary has been updated to also accept an object parameter. Update (August 16): Looks like this is a regression—Chrome takes a string once again. The final parameters in both cases are callbacks for successes and errors.

function onSuccess(stream) {
    var output = document.getElementById('output'), // a video element
        source;
 
    output.autoplay = true; // you can set this in your markup instead
 
    if (!is_webkit) {
        source = stream;
    }
    else {
        source = window.webkitURL.createObjectURL(stream);
    }
 
    output.src = source;
}

The success callback gives us access to a Stream object which, with an extra bit of feature-sniffing magic, we pass on to the src attribute of our video element. It is important that your video element has its autoplay attribute set, or you will only see the first frame of video.

Those wishing to future-proof their implementations would do best to check out the gUM Shield, which anticipates the use of browser prefixes for other browser implementations as they come out.

The potential of getUserMedia is larger than most people realize! While there are a few great demos currently out there, most of them are focused on personal use. This is a great start and it will be exciting to see how it plays out for games and chat applications. Did someone say native browser chat roulette?

27 thoughts on “Getting started with getUserMedia

  1. Is there any user interaction required when requesting a webcam stream? What’s to prevent malicious websites from recording your activity without your permission?!?

  2. for now you have to download the dev versions of these browsers ( opera and chrome ) i would say that is the only user interaction required ( other than enabling the getMediaStream() ).

  3. Well, the device (camera) still needs the permission from the user – before it can work and grab the data. It’s similiar to the geolocation & co. where safety comes first :)

  4. “it will be exciting to see how it plays out for games and chat applications.”
    I’m always very surprise that nobody seems to think at educational and learning apps. For example using the micro for recording the user and sending the file on the server will be very very valuable for learning foreign language. I’m waiting for this since 10 years.

    • Why wait when you can build it yourself? ;)

      I’ve also used this stuff in Flash to build a basic motion-detection/home security system. There’s quite a lot of applications for this stuff in fact!

  5. Nice article,
    is there any way for streaming Audio only ? how to gather audio sample data and convert it into base64 for broadcasting ?

    thannks in advance

      • Thanks for your quick reply,
        As i already set “audio” attribute to “true” and “video” attribute to “false” in getUserMedia() and its asking permision to access my Microphone, but how to capture audio stream sample data ? my code is :

        var audio = document.getElementById(‘ttaudio’);
        if(navigator.webkitGetUserMedia) {

        navigator.webkitGetUserMedia({audio:true}, function(stream){
        audio.src = window.webkitURL.createObjectURL(stream);
        console.log(s);
        });
        }

        Is there any need to set Timmer for getting streaming data from mic ? How can i log my mic streaming ?

        I already ask this problem on :

        http://stackoverflow.com/questions/11147755/capturing-microphone-using-html-5-and-broadcast-using-socket-io

        Thanks

  6. Hey there I created more or less similar code but it only works on Opera (havent tested Mozila)
    on Canary Chrome i am getting
    Uncaught TypeError: Not an object. @ n.webkitGetUserMedia(‘video, audio’, onSuccess, onError);
    although hasGetUserMedia() returns as true ( checking if it has it on )

    Any ideas?
    Works like a charm on opera :D

  7. Hi, I could do the example, but what if the browser has getusermedia avaiable but no cams?? What to get the number of cams avaiable???

    Thanks in advance,
    Rodrigo.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *