How to Use getUserMedia()
Learn how to use getUserMedia() to access audio and video input from the user.
The getUserMedia() method is available through the MediaDevices object exposed by navigator.mediaDevices.
Warning: Although the navigator object still exposes a deprecated getUserMedia() method, it is recommended to use getUserMedia() through the mediaDevices object for consistency.
Here’s how you can use the getUserMedia() method:
Assume we have a button:
1 | <button>Start streaming</button> |
We wait for the user to click this button and then call the navigator.mediaDevices.getUserMedia() method.
To request a video input, we use the following code:
1 | navigator.mediaDevices.getUserMedia({ |
We can also specify specific constraints for the video:
1 | navigator.mediaDevices.getUserMedia({ |
To get a list of all the constraints supported by the device, you can call navigator.mediaDevices.getSupportedConstraints().
If you only want the audio input, you can pass audio: true:
1 | navigator.mediaDevices.getUserMedia({ |
And if you want both audio and video:
1 | navigator.mediaDevices.getUserMedia({ |
The getUserMedia() method returns a promise, so we can use async/await to get the result in a stream variable:
1 | document.querySelector('button').addEventListener('click', async (e) => { |
Clicking the button will trigger a browser panel to ask for permission to use the media devices.
Once we have the stream object obtained from getUserMedia(), we can use it for various purposes. One immediate use is to display the video stream in a video element on the page:
1 | <button>Start streaming</button> |
1 | document.querySelector('button').addEventListener('click', async (e) => { |
Here is an example of how getUserMedia() can be used to access the video camera and play the video in a page. You can find the example on CodePen.
1 | <button id="get-access">Get access to camera</button> |
The JavaScript code listens for a click on the button and then calls navigator.mediaDevices.getUserMedia() to request the video stream. The name of the camera used can be obtained by calling stream.getVideoTracks() on the result of getUserMedia().
The stream is set as the source object for the video tag to enable playback.
1 | document |
You can specify additional requirements for the video stream by providing arguments to getUserMedia():
1 | navigator.mediaDevices.getUserMedia( |
To obtain an audio stream, you would request the audio media object as well and call stream.getAudioTracks() instead of stream.getVideoTracks().
After 3 seconds of playback, the video streaming can be stopped by calling track.stop().
tags: [“getUserMedia”, “MediaDevices”, “video input”, “audio input”, “constraints”, “permission”, “stream”, “video element”]