Click here to Skip to main content
Click here to Skip to main content

Use JavaScript and WebRTC API to access your Camera and Microphone from browser

By , 13 Feb 2013
Rate this:
Please Sign up or sign in to vote.

Introduction 

With the latest version of Google chrome, Opera and other web browsers that support WebRTC, also with the rise of HTML5 and the features that helps to access user devices and files has made the capture of Video/Audio a simple task and without downloading any plugin like what is the case for Facebook, GTalk or skype, this access could be allowed using the WebKit GTK+ which is already in Google latest Chrome and other web browsers to capture the video/audio from camera/microphone and HTML5 video element to display it.

In This article we will see how it very simple to implement this feature using the webkitGetUserMedia API developed by WebRTC and the HTML5 video element.

Background

Before you can start using these features/API you need to install the latest version of a Google Chrome ;Chrome Canary for example, or Opera, or simply update your current version. When you finish the installation, you could than try out my demo, by only copying the enclosed page in an HTTP Server and then open it using the installed web browser. 

The basics of programming using JavaScript and HTML5 are needed to understand the code, but no need to be a web programmer to test this demo.  

Using the code 


1 - Getting access to your Camera and Microphone :
 

To get the MediaStream which is an object that represent a stream of the local video and/or audio obtained from your camera and microphone, a getUserMedia() method is needed.
The call of this method differ from browser to other, it's why in my code I have used the try/catch statement to implement the two call of this method, you could also use the if/else to process depending on the browsers.
navigator.webkitGetUserMedia("audio, video", OnSuccess, OnError); 

or 

navigator.webkitGetUserMedia({ video: true, audio: true }, onSuccess, onError);

The two first arguments indicates to the method which devices will be accessed video or/and audio ; camera or /and microphone. 

The OnSuccess and OnError are two functions that should be defined to handle the stream when the device access is successful or in case of error, note that you could name these two functions as you want e.g : OnStreamOk and OnStreamFail.

When the getUserMedia is called a permission message is prompted for permission to use the devices; camera and microphone before any data is accessible by the JavaScript code of the page. 
You should accept the use of your Cam and micro.

You should allow the use of your Cam and micro, when the navigator display this message.

2 - Display the Media Stream :  

To display the stream that you get after using the getUserMedia() method, we will use an HTML5 video tag.

Firstly, we should define the OnSuccess and OnError method :  

function onSuccess(stream) { 
var videoElement = document.getElementById("video1"); 
var StreamSource; 
videoElement.autoplay = true; 
if (!isWebkitBrowser) {
        StreamSource = stream;
    }
    else {
        StreamSource = webkitURL.createObjectURL(stream);
    } 
videoElement.src = StreamSource; 
} 

source and isWebkitBrowser variables are defined in the page, isWebkit are updated depending on the browser version when using the getUserMedia method :

try {
//for Opera or others
isWebkitBrowser= false;
navigator.webkitGetUserMedia({ video: true, audio: true }, onSuccess, onError);
} catch (e) {
//for webkit
isWebkitBrowser= true;
navigator.webkitGetUserMedia('video, audio', onSuccess, onError);
}

Now, let's define the OnError function that will be launched when the access to the devices is denied:

function onError(er) {
    alert("Error function reached, Can't Access the user devices")
}

When the function is called in case of error ,an alert is prompted Wink | <img src=  

3 - Test the demo 

To test the demo you should simply download the page.zip file, unzip it and copy it to an HTTP Server, a Wamp Server for example.

Copy the page in the WWW folder:

Make sure that the Server is started and Acces the page using the web browser. You could also test it an a smartphone Android Chrome or other browsers Wink

Accept the use of your Camera and Microphone and enjoy Smile 

4 - Debug the code 

If you have some issues with the code or the camera/microphone doesn't respond to the access by JavaScript code, you could debug the code to see where the problem come from by placing a breakpoints in the JavaScript code ; place "debugger;" key word like this :

When the OnSuccess() or the OnError() method is called the JavaScript code execution will stop in the breakpoint (debugger;), when the element inspector of chrome or FireBug in FireFox is openned :

  

You could now use Expression watchers or evaluate your the expressions in the console, to track the variables values and how it changes.

 

Now, you could see the object value ; attributes and methods prompted in the console :

 

Note : 

To activate the WebRTC feature in chrome, access this page in Chrome chrome://flags/ and search through the list of features WebRTC and activate it :

Points of Interest 

Another WebRTC API could be used for a browser-to-browser Real Time Communication is a PeerConnection API, I haven't yet tested it, it seems amazing and more fast than passing by a server, as I know if there is a firewall configs between the two peers these could still prevent connectivity and cause problems for the PeerConnection API, coding with JavaScript and on browsers is the future of  Web apps. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Saad Mousliki
Software Developer IWS
Morocco Morocco
currently an IT Support and Evangelist Professional
specialized in Web and software: JavaScript; Wakanda; ASP.NET, C #, WPF, JAVA, C... (SQL Server, jQuery, AJAX, ...)
I am also interested to mobile: Kinect, iOS, PhoneGap,Windows Phone and Android
To contact me : saadmos06@gmail.com
Follow on   Google+

Comments and Discussions

 
Questionvery interesting PinmemberEmiel Duivenvoorden6-Nov-12 1:20 
AnswerRe: very interesting Pinmembersaadmos6-Nov-12 3:54 
GeneralRe: very interesting Pinmemberlazywill8-Nov-12 16:45 
GeneralRe: very interesting Pinmembersaadmos8-Nov-12 23:17 
GeneralRe: very interesting Pinmembersaadmos8-Nov-12 23:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 13 Feb 2013
Article Copyright 2012 by Saad Mousliki
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid