Build A (local) Webcam With WebRTC In Less Than 20 Lines!

WebRTC is all kinds of super ninja epic awesomesauce stuff. If you haven’t looked in to it yet, you’re going to want to get on that soon. I’d suggest starting with the HTML5 Rocks post on getUserMedia.

Build Your Own Web Cam

Just how awesome is it? You can build a web page that shows your webcam and hooks up your microphone in 20 lines of JavaScript… and that includes feature detection with an error message for browsers that don’t support it!

(function(){
  var mediaOptions = { audio: false, video: true };

  if (!navigator.getUserMedia) {
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  }

  if (!navigator.getUserMedia){
    return alert('getUserMedia not supported in this browser.');
  }

  navigator.getUserMedia(mediaOptions, success, function(e) {
    console.log(e);
  });

  function success(stream){
    var video = document.querySelector("#player");
    video.src = window.URL.createObjectURL(stream);
  }
})();

The gist of it is this:

The first few line sets the options to ignore audio and get video. The next 3 lines do a bit of browser normalization to make sure “getUserMedia” is available. Then do the other half of feature detection, and exit the IIFE if it’s not available at all. Once you’re certain it’s ok, run the getUsermedia with the options that were previously set. If there’s an error, report it via console. If there’s no error, run the success function and tell the <video> element to play the video from the webcam.

You’ll need a couple lines of HTML and to make it look nice, a bit of CSS, too.

<!doctype html>
<html>
  <head>
    <title>WebRTC WebCam</title>
    <link rel="stylesheet" href="webcam.css"/>
    <script src="webcam.js"></script>
  </head>
  <video id="player" autoplay="true"></video>
</html>


body {
  margin: 0px;
  padding: 0px;
}

#player {
  width: 100%;
  height: 100%;
}

Note the use of the “autoplay” setting in the <video> element. Without this, you’ll just get a freeze frame from the video. The CSS just makes the video element huge, which is fun.  

How Well Does It Work?

See for yourself, with this fancy schamcy JSBin (and make sure you hit “allow” when your browser prompts you to access your camera:

WebRTC WebCam

If this doesn’t work for you, you’ll end up seeing a link that just says “WebRTC WebCam”… which won’t surprise me if you’re reading this in an RSS reader or in Safari or Internet Explorer. WebRTC is only workable in Chrome, Firefox and Opera at the time that I’m writing this. Be sure to check the usual “is it ready?” sites, for more info:

http://caniuse.com/#feat=stream

http://iswebrtcreadyyet.com/

Be More Awesome

From here, there are a lot of things you could do with WebRTC, including real-time chat rooms with audio and video. This gets pretty hairy pretty quickly, though. You’ll need to get some crazy STUN server awesomeness going in order to get peer to peer negotiations of video and audio formats handled. It’s a bit of a mess, at the moment, quite honestly. But the future looks amazing. And I’m diving in head first.


Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Derick Bailey

Derick Bailey is an entrepreneur, problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He runs SignalLeaf.com - the amazingly awesome podcast audio hosting service that everyone should be using, and WatchMeCode.net where he throws down the JavaScript gauntlets to get you up to speed. He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: SignalLeaf, WatchMeCode, Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in HTML5, Javascript, WebRTC. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://aashishkoirala.github.io/ Aashish Koirala

    Awesomesauce, indeed!

  • khalidabuhakmeh

    Very cool, how do you save videos to the server using WebRTC?

    • Bogdan Maier

      well you read from your stream, where peer 1 is you peer 2 is the server, and you dont forward the data you create a new video file with an encoding class.For the rest there is google.

  • http://linkedin.com/in/chrisallenstudio Zias Zias

    Nice. Any suggestions or options for an IE10 fallback. We do this in ActiveX now, but need to support IE10 and greater like yesterday. LOL

    • http://mutedsolutions.com Derick Bailey

      Flash, ActiveX or some other plugin that IE supports would be your only option. IE and Safari don’t have any WebRTC support yet. Until they do, it’s plugins, plugins, plugins.

      • JohnBubriski

        Ah OK, makes sense. Thanks!

  • JohnBubriski

    Your gist worked great in FireFox locally, and the JS Bin version worked in Chrome. However, the gist did not work in Chrome locally. An idea why that would be?

    I don’t get the “Allow” message, I just get this error message (in Chrome 33):

    NavigatorUserMediaError {constraintName: “”, message: “”, name: “PermissionDeniedError”}

    • http://mutedsolutions.com Derick Bailey

      by “locally” do you mean putting the code in to a .js or .html file and loading it from your file system? chrome doesn’t allow that. you have to run the code from a web server – even a local web server like “php -S”, nodejs, python, etc. Any local web server will work.

      • igor

        Useful answer, by the way)