Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Media Capture and Streams

Capturing Media with getUserMedia

Capture camera and microphone with navigator.mediaDevices.getUserMedia: show a live preview, handle every error, stop devices and test without hardware.

Every call starts with media: a video from the camera, audio from the microphone. The browser API that provides it is navigator.mediaDevices.getUserMedia(). It asks the user for permission, opens the device and returns a promise of a MediaStream. You then show that stream in a <video> element and, later, hand its tracks to an RTCPeerConnection.

On this site. The sandboxed preview has no camera or microphone access, so the code that opens real devices is shown read-only, next to runnable versions that handle the failure and a synthetic camera (a canvas) you can use everywhere in this course. The synthetic camera produces a real MediaStream with a real video track, so everything you learn applies unchanged to real hardware.

The minimal capture

JavaScript
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
const video = document.querySelector('video');
video.srcObject = stream;      // not video.src

And the markup:

HTML
<video autoplay playsinline muted></video>

Why those attributes?

  • srcObject connects a MediaStream to the element. (src is for URLs.)
  • autoplay starts playback as soon as frames arrive.
  • playsinline stops iPhones from jumping to full screen.
  • muted on your own preview is essential: if you play your microphone through your speakers you create an echo loop. Mute the local preview, never the remote video.

Asking for what you need

The argument is a constraints object. true means "any device of this kind". Leaving a kind out (or false) means you do not want it:

Request Result
{ video: true } Camera only
{ audio: true } Microphone only
{ video: true, audio: true } Both (one prompt, or two in some browsers)
{ video: { width: 1280, height: 720 } } Camera, preferring 720p

Detailed constraints get their own lesson: constraints and devices.

Handling errors properly

getUserMedia rejects with a DOMException. The name tells you what to show the user:

JavaScript
async function openCamera() {
  try {
    return await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
  } catch (err) {
    switch (err.name) {
      case 'NotAllowedError':
        showHelp('Camera access was blocked. Click the camera icon in the address bar to allow it.');
        break;
      case 'NotFoundError':
        showHelp('No camera or microphone was found.');
        break;
      case 'NotReadableError':
        showHelp('Your camera is in use by another app.');
        break;
      case 'OverconstrainedError':
        showHelp('This camera cannot satisfy: ' + err.constraint);
        break;
      default:
        showHelp('Could not open the camera: ' + err.name);
    }
    return null;
  }
}

Run the real thing below. In the sandboxed preview it cannot succeed, so you will see an error name (usually NotAllowedError or SecurityError) or the timeout message, depending on your browser. The timeout is our own addition so the demo never hangs on a permission prompt. On a normal page of your own, with a camera, the same code shows your face.

Request the camera and handle the failure

A synthetic camera for development and tests

Real cameras are awkward in automated tests, on servers and in demos. A canvas can play the part. canvas.captureStream(fps) returns a MediaStream with a live video track, and you decide what to draw:

A fake camera you can use anywhere

You can now write const stream = USE_FAKE ? fakeCamera() : await navigator.mediaDevices.getUserMedia(...) and test the rest of your app without hardware.

Stopping the camera

A stream does not stop when you remove the <video>. The camera light stays on until every track is stopped:

JavaScript
stream.getTracks().forEach((track) => track.stop());
video.srcObject = null;

Always stop tracks when leaving a call, when switching cameras and when a component unmounts. In single-page apps, forgetting this is the most common cause of "my camera light stays on".

Audio notes

  • Audio from getUserMedia has echo cancellation, noise suppression and automatic gain on by default. That is right for calls and wrong for music (see constraints).
  • Wear headphones when testing two tabs on one machine, or the microphone will pick up the speakers.
  • A <video> that has audio but not muted needs a user gesture before it autoplays in some browsers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you display a MediaStream in a video element?

    srcObject accepts a MediaStream (or Blob). The src attribute expects a URL.
  2. 2. Why should your own local preview be muted?

    Playing your own microphone through your speakers creates an echo loop. Mute the local preview; keep remote video unmuted.
  3. 3. Which error means another application is using the camera?

    NotReadableError means the device exists but cannot be opened, often because it is busy.
  4. 4. What turns the camera light off?

    The hardware is released when all tracks that use it are stopped.

Summary

  • getUserMedia(constraints) prompts for permission and resolves to a MediaStream; attach it with video.srcObject.
  • Use autoplay playsinline muted on the local preview.
  • Handle NotAllowedError, NotFoundError, NotReadableError and OverconstrainedError with helpful messages.
  • A canvas captureStream() is a handy fake camera for demos and tests.
  • Always stop all tracks to release the device.

Next: Constraints and Devices