• We Code
  • We Design
  • We Develope
  • We Write
  • We Share


Wednesday, April 24, 2013

getUserMedia Introduction With The simple Source Code

getUserMedia  has came in web by Opera first . Opera called it <Device> which was used to get access to the native hardware like camera and mic of the user pc .

<device type="media" onchange="update(this.data)"></device>
<video autoplay></video>
  function update(stream) {
    document.querySelector('video').src = stream.url;

This was the syntax of < device>
Soon after  the <device> the WhatWG  decided to bring a javascript api named navigator.getUserMedia()  . This API is the part of Web RTC which means web real time communication.

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

if (getTheMedia ()) {
  // its nice  to go!
} else {
  alert('your browser is not getUserMedia()  enabled ');

 The getUserMedia ask your permission for accessing your webcam and mic.

The navigator.getUserMedia take the first parameter {audio: true, video: true} and then couple of optional call back .

so the syntax of navigator.getUserMedia look like this.

navigator.getUserMedia({audio: true, video: true}, ifSuccessfull, ifError);

 function ifSuccessfull(stream) {
  // use the stream for further use ...
  function error(){
  alert("your browser is not getUsermedia enabled")
 getUserMedia enable you to access the hardware like camera and mic without any plugin . After accessing the user media you need to add this to the <video> src .The code will look like the below. 

function onFail(e) {
  video.src = 'fallbackvideo.webm';

function onSuccess(stream) {
  video.src = window.URL.createObjectURL(stream);

if (!navigator.getUserMedia) {
} else {
{audio: true, video: true}
, onSuccess, onFail);

 Further you can add the css3 filter too it like you can rotate the video .And you can play with this Web Rtc API

Check The simple Demo here


Post a Comment