MediaDevices API example

MediaDevices API example: getSupportedConstraints(), enumerateDevices(), getUserMedia(), getDisplayMedia(), selectAudioOutput(), devicechange.

The problem

A page cannot open a camera, a mic, or the screen by itself. Device names stay blank on purpose until the browser gets a yes.

The method

navigator.mediaDevices is the door. Five methods, one event. Each snippet is the call from the docs. Run applies it here.

getSupportedConstraints()

Which constrainable properties this browser understands. Not what the hardware can do.

const support = navigator.mediaDevices.getSupportedConstraints()
Result

enumerateDevices()

Lists cameras, mics, and speakers. Labels stay blank until a stream has been granted. Run it again after getUserMedia().

const devices = await navigator.mediaDevices.enumerateDevices()
Result

getUserMedia()

Asks for a camera or a mic. A yes returns a MediaStream. Audio runs the same call with { audio: true }.

const stream = await navigator.mediaDevices.getUserMedia({
  audio: false,
  video: true,
})
video.srcObject = stream

getDisplayMedia()

Asks for a screen, a window, or a tab. Same MediaStream shape as a camera.

const stream = await navigator.mediaDevices.getDisplayMedia({
  video: true,
})
video.srcObject = stream

selectAudioOutput()

Prompts for a speaker. Then setSinkId() routes a short tone to it.

const output = await navigator.mediaDevices.selectAudioOutput()
await audio.setSinkId(output.deviceId)

devicechange

Fires when a camera, mic, or speaker is attached or removed. Plug something in while this is listening.

navigator.mediaDevices.addEventListener("devicechange", () => {
  navigator.mediaDevices.enumerateDevices()
})

All Web API labs

  • HTML usermedia element example
  • MediaRecorder API example
  • Web Audio API example