Skip to content
Tutorials Center
My learning

Topics

Lesson 102 of 122 ยท Web APIs

Camera, Microphone and MediaRecorder

Capture live video and audio with getUserMedia, handle permissions and errors, record streams with MediaRecorder, and play back or download the result.

Video calls, voice notes, QR scanners and screen recorders all start the same way: the page asks the browser for a media stream and then does something with it. HTML has two key pieces. navigator.mediaDevices.getUserMedia() asks for the camera and microphone, and MediaRecorder turns any stream into a recorded file that you can play back or download.

Camera and microphone are powerful and private, so the browser gates them heavily. This lesson shows the whole flow, including the error cases you must handle. Because the sandboxed preview in this site cannot open your devices, the live examples record streams the page generates itself (a canvas animation and a synthesized tone). The recording code is identical for real devices.

Rules of access

  • The page must be served from a secure context (HTTPS, or localhost while developing).
  • The browser shows a permission prompt the first time, and remembers the answer per site.
  • The call must usually come from a user gesture, such as a button click.
  • The user can revoke access at any time, and an indicator in the browser shows when a camera or microphone is live.
  • A page can delegate or block the feature for embedded frames with a Permissions-Policy header or the allow attribute on an <iframe> (for example allow="camera; microphone").

Requesting a camera and microphone

getUserMedia() takes constraints describing what you want and returns a promise for a MediaStream.

HTML
<video id="preview" autoplay muted playsinline></video>
<button id="start">Start camera</button>

<script>
  document.getElementById("start").addEventListener("click", async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { width: { ideal: 1280 }, height: { ideal: 720 }, facingMode: "user" },
        audio: true,
      });
      document.getElementById("preview").srcObject = stream;
    } catch (error) {
      console.error(error.name, error.message);
    }
  });
</script>

A few details matter here:

  • srcObject (not src) connects a stream to a <video>. Add autoplay and playsinline so it starts without fullscreen on phones, and muted so you do not hear your own microphone echo.
  • Constraints use ideal, min, max and exact. Prefer ideal; exact fails if the device cannot match. facingMode: "environment" asks for a phone's rear camera.
  • Pass audio: true for just the microphone, video: true for just the camera.

Errors you must handle

The promise rejects with a DOMException. The name tells you what happened:

error.name Meaning
NotAllowedError The user (or a permissions policy) denied access
NotFoundError No camera or microphone matches the request
NotReadableError The device exists but is in use by another app
OverconstrainedError An exact constraint could not be met
SecurityError / TypeError Insecure context or invalid constraints

Show a friendly message for each, and always give a non-camera alternative where possible (a file upload, for example).

Ask for the microphone and report the result

In this sandboxed preview you will most likely see the "Blocked" message, which is the correct behavior: an embedded frame without permission cannot open your devices. On a real page you would get the browser's permission prompt instead.

Listing devices and stopping tracks

A stream holds one or more tracks (getVideoTracks(), getAudioTracks()). Calling track.stop() releases the hardware and turns off the browser's camera light. Stop tracks when you are done: leaving them running drains the battery and keeps the indicator lit.

navigator.mediaDevices.enumerateDevices() lists cameras and microphones. Labels stay empty until the user has granted permission once. Pass a deviceId in the constraints (video: { deviceId: { exact: id } }) to pick a specific device.

Recording with MediaRecorder

MediaRecorder records any MediaStream: a camera, a microphone, a screen capture (getDisplayMedia()), a <canvas> or an audio graph. The workflow is:

  1. Create it: new MediaRecorder(stream, { mimeType }).
  2. Collect data in the dataavailable event (each event carries a Blob).
  3. Call start(), and later stop().
  4. In the stop event, merge the chunks into one Blob and use it.

Browsers support different formats (WebM in Chromium and Firefox, MP4 in Safari), so ask which one is available:

JavaScript
const candidates = ["video/webm;codecs=vp9,opus", "video/webm", "video/mp4"];
const mimeType = candidates.find((type) => MediaRecorder.isTypeSupported(type));

A recorder you can run here

A canvas can be captured as a video stream with canvas.captureStream(fps), so we can record without any permission. The demo draws a moving circle, records for three seconds, then plays the recording back and offers it for download.

Record a canvas animation

Swap the canvas stream for a camera stream from getUserMedia() and the rest of the code stays the same. Two details are worth noting. recorder.start(1000) would emit a chunk every second, which is useful for long recordings you upload as they go. And the final Blob is only as good as the MIME type you chose, so keep recorder.mimeType for the file extension and the <video> or <audio> element.

Recording only audio

A voice recorder is the same pattern with audio: true and an <audio controls> element for playback. You can also record audio you synthesize: connect nodes to audioContext.createMediaStreamDestination() and record its stream. The next lessons build on that idea.

Screen capture

navigator.mediaDevices.getDisplayMedia({ video: true }) asks the user to choose a screen, window or tab and returns a stream you can display or record the same way. It always requires a user gesture and always shows the browser's own picker, so a page can never record the screen silently.

Privacy and good practice

  • Ask only when the user clicks something that obviously needs it ("Take photo"). A permission prompt on page load is often refused and may be remembered as a "no".
  • Explain why you need access before triggering the prompt.
  • Stop tracks as soon as you finish, and show a visible "recording" indicator in your own interface too.
  • Handle the "denied" state with instructions for changing the site setting, and offer an alternative such as <input type="file" accept="image/*" capture> (see Files, File Uploads and the FileReader API).
  • Do not upload recordings without clear consent, and tell people what you do with them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which property connects a MediaStream to a video element?

    video.srcObject = stream attaches a live stream. The src attribute is for URLs.
  2. 2. What does a NotAllowedError from getUserMedia() usually mean?

    NotFoundError means no device, NotReadableError means the device is busy, and NotAllowedError means permission was refused.
  3. 3. How do you finish a recording with MediaRecorder?

    Each dataavailable event gives a Blob chunk. In the stop handler you merge them with new Blob(chunks) to get the recording.
  4. 4. Why call track.stop() when you are done with a camera stream?

    Stopping tracks releases the device. Otherwise the camera light stays on and the battery drains.

Summary

  • getUserMedia() needs a secure context, a permission and usually a user gesture; it returns a MediaStream of audio and video tracks.
  • Attach streams to <video> with srcObject, and handle NotAllowedError, NotFoundError and NotReadableError with friendly messages.
  • MediaRecorder records any stream: collect dataavailable chunks and build a Blob in the stop event; check formats with isTypeSupported().
  • canvas.captureStream() and getDisplayMedia() give you other kinds of streams to record.
  • Respect privacy: ask at the right moment, stop tracks promptly and offer alternatives.

Next lesson: Web Audio API Basics, where you generate and shape sound with code.