Click here to Skip to main content
15,891,431 members
Articles / Web Development / HTML

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

Rate me:
Please Sign up or sign in to vote.
4.79/5 (14 votes)
2 Nov 2012CPOL4 min read 77K   2.4K   33  
How to access Camera and Microphone using JavaScript, HTML5 and a new browser
This is an old version of the currently published article.

Download page.zip 

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.

 

Image 1 

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 and 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 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.
JavaScript
navigator.webkitGetUserMedia("audio, video", OnSuccess, OnError); 

or 

JavaScript
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.

Image 2


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 getUserMeda() 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:

Image 4 

 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 | <img src=  

Accept the use of your Camera and Microphone and enjoy Smile | <img src= 

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 :

Image 7

 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 :

Image 8  

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

Image 9 

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

Image 10 

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 :

 Image 11

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.  






License

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


Written By
Technical Writer SaadMos
Morocco Morocco
currently an IT Manager (ITSM), with background in Web, Mobile and Could
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, hybrid mobile app, and Android
To contact me : saadmos06@gmail.com

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.