HTML usermedia element example

HTML usermedia, camera, and microphone elements. The browser draws the permission control and returns the stream. An alternative to getUserMedia().

The problem

Manage permission with getUserMedia() is often cumbersome. You have to check for support, request the stream, handle errors, and manage the tracks. If user denies, you can’t ask again.

The method

Three tags. <usermedia> is both tracks, stream on success. <camera> is video. <microphone> is audio. Browser manages permission, and paint the buttons.

The stage

Click a control. The track lands here.

The example

<usermedia>
  <button type="button" disabled>No usermedia</button>
</usermedia>
<camera>
  <button type="button" disabled>No camera</button>
</camera>
<microphone>
  <button type="button" disabled>No microphone</button>
</microphone>
<video autoplay playsinline muted></video>
<p></p>
usermedia,
camera,
microphone {
  margin: 0 0.5rem 0.5rem 0;
  color: #fff;
  background-color: #111;
  font-size: 16px;
  border-radius: 8px;
  opacity: 1;
}

usermedia:granted,
camera:granted,
microphone:granted {
  background-color: #1f7a4d;
}

usermedia button,
camera button,
microphone button {
  font: inherit;
  padding: 0.45rem 0.8rem;
  border: 1px solid #ccc;
  border-radius: 8px;
  background: #fff;
}

#preview {
  display: block;
  width: min(100%, 28rem);
  margin-top: 1rem;
  aspect-ratio: 16 / 9;
  border-radius: 8px;
  background: #111;
  object-fit: cover;
}

#heard {
  margin: 0.75rem 0 0;
  color: #666;
}
const preview = document.querySelector("#preview")
const heard = document.querySelector("#heard")
const both = document.querySelector("#both")
const cam = document.querySelector("#cam")
const mic = document.querySelector("#mic")

if (both.setConstraints) {
  both.setConstraints({
    video: { width: 1280, height: 720 },
    audio: { echoCancellation: true },
  })
  both.addEventListener("stream", () => {
    preview.srcObject = both.stream
    heard.textContent = ""
  })
}

if (cam.setConstraints) {
  cam.setConstraints({ width: 1280, height: 720 })
  cam.addEventListener("track", () => {
    preview.srcObject = new MediaStream([cam.track])
  })
}

if (mic.setConstraints) {
  mic.setConstraints({ echoCancellation: true })
  mic.addEventListener("track", () => {
    heard.textContent = mic.track.label
  })
}

All Web API labs

  • MediaRecorder API example
  • Web Audio API example
  • Web Speech API example