Cameras and microphones have been common on desktop and laptop computers for a long time, and with the rise of mobile devices they’ve become extremely prevalent—almost ubiquitous. But for years, we’ve had to rely on third-party plug-ins, such as Flash and Java, to get audio and video input on the Web, so a native input method is more than overdue.
This native input comes in the shape of the getUserMedia() method, part of the WebRTC project, which I’ll discuss in more detail in Chapter 9. The getUserMedia() method is on the navigator object, and takes up to three arguments: The first is for options about the stream, such as whether to accept only audio, only video, or both; the second is a callback fired when a successful connection is made; and the third, which is optional, is a failure callback:
navigator.getUserMedia({options}, success, failure);
As with the Geolocation and Fullscreen APIs, accessing the user’s camera or microphone has privacy implications, so many browsers provide an on-screen prompt asking for the user’s permission to access the device. On devices with more than one camera, some user agents offer a native control to switch between them.
A media stream requires a special element in order to be displayed, either the new video or audio HTML5 element (depending on the stream content). I introduce these new elements fully in Chapter 9, but for the purposes of the following demonstration, using a video stream, you need the following markup somewhere on your page:
<video autoplay></video>
When the successful callback is fired from getUserMedia(), the media stream is returned with a unique ID (provided by you), which will be supplied to the video element. The following code shows a basic example, which I’ve annotated and will explain after:
1 navigator.getUserMedia({video:true}, function (stream) { 2 var video = document.querySelector('video'); 3 video.src = window.URL.createObjectURL(stream); });
In line 1, I’ve supplied two arguments to the getUserMedia() method: The first is the stream options where I’m flagging that I want to get video, no audio; and the second is the callback function where I’ve given the result a unique ID of stream. In the next line 2, I’ve used querySelector() to assign the video element to the video variable so that in line 3, I can use the createObjectURL() method to convert stream into a URL and set it as the src attribute of the video element. No failure callback is supplied.
To try this for yourself, see the file getusermedia.html—you’ll need to have a video on your device to see the file in action.