41
navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
If we know that getUserMedia() is supported, we call startVideo(). If not, we display
an alert box:
function eventWindowLoaded() {
if (userMediaSupported()) {
startVideo();
} else {
alert("getUserMedia() Not Supported")
}
}
Next, we find the existing getUserMedia() method for the current browser and set the
local navigator.getUserMedia() function to its value. Again, we do this because sup‐
port is not universal, and this step will make it much easier to reference getUserMe
dia() in our code.
Next we call the getUserMedia() function, passing three arguments:
• An object with Boolean properties media that we want to capture (video:true and/
or audio:true) (At the time this was written, the audio property was not support‐
ed.)
• A success callback function.
• A fail callback function.
function startVideo() {
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia;
navigator.getUserMedia({video: true, audio:true}, mediaSuccess, mediaFail);
}
The mediaFail() function simply creates an alert() box to show us an error. Most
likely, when you try this example, you will get error code 1, which means “permission
denied.” This error will occur if you are trying to run the example locally from the file
system. You need to try all the getUserMedia() examples from a web server, running
either on your own machine or on the Internet.
function mediaFail(error) {
//error code 1 = permission Denied
alert("Failed To get user media:" + error.code)
}
The mediaSuccess() function is the heart of this application. It is passed a reference to
the video object from the webcam (userMedia). To utilize this, we need to create a URL
that points to the object representing the user media so that our <video> object has a
source that it can use to start showing video.
Capturing Video with JavaScript | 371