What is the getUserMedia web API?

The web keeps growing and getting more sophisticated. Due to this, more support is being poured into the web, giving it the ability to do stuff native to the operating system.

Such support includes the getUserMedia API.

getUserMedia API

This API is used for accessing and controlling the media devices like the camera in our device.

It is available in the navigator.mediaDevices object.

Syntax

navigator.mediaDevices.getUserMedia()

Parameters

You can pass an object to getUserMedia if you want to access the video or the audio stream of your device.

 navigator.mediaDevices.getUserMedia({
        video: true,
        audio: false
    })

Above, we only get the video input and no audio input.

Permissions

Upon calling getUserMedia, the browser will prompt you for permission to use a media input. The media input can be the camera, a screen sharing service, a virtual video source, an external video camera, and for audio input it can be the system microphone, external microphone, etc.

Return value

getUserMedia returns a Promise which resolves to a MediaStream object.

Example

A more sufficient use of getUserMedia is with the video and canvas elements. With both these elements and getUserMedia, we can create a camera app in our browser!

    <video id="video"></video>
    navigator.mediaDevices.getUserMedia({
            video: true
        }).then((stream) => {
            video.srcObject = stream
            video.play()
        })

In the above example, we streamed the video input from a web camera to a video element. This will play the live feed from the web camera in the video element.

Free Resources