MDN self-hosted library · e01.org

MediaDevices: getUserMedia() method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

html
<iframe src="https://mycode.example.net/etc" allow="camera; microphone">
</iframe>
js
async function getMedia(constraints) {
  let stream = null;

  try {
    stream = await navigator.mediaDevices.getUserMedia(constraints);
    /* use the stream */
  } catch (err) {
    /* handle the error */
  }
}
js
navigator.mediaDevices
  .getUserMedia(constraints)
  .then((stream) => {
    /* use the stream */
  })
  .catch((err) => {
    /* handle the error */
  });
js
getUserMedia({
  audio: true,
  video: true,
});
js
getUserMedia({
  audio: true,
  video: { width: 1280, height: 720 },
});
js
getUserMedia({
  audio: true,
  video: { width: 1280, height: 720, resizeMode: "crop-and-scale" },
});
js
getUserMedia({
  audio: true,
  video: {
    width: { min: 1280 },
    height: { min: 720 },
  },
});
js
getUserMedia({
  audio: true,
  video: {
    width: { min: 1024, ideal: 1280, max: 1920 },
    height: { min: 576, ideal: 720, max: 1080 },
  },
});
js
getUserMedia({
  audio: true,
  video: {
    width: { ideal: 1280 },
    height: { ideal: 720 },
  },
});
js
getUserMedia({
  audio: true,
  video: { facingMode: "user" },
});
js
getUserMedia({
  audio: true,
  video: {
    facingMode: { exact: "environment" },
  },
});
js
getUserMedia({
  video: {
    deviceId: myPreferredCameraDeviceId,
  },
});
js
getUserMedia({
  video: {
    deviceId: {
      exact: myExactCameraOrBustDeviceId,
    },
  },
});
js
// Prefer camera resolution nearest to 1280x720.
const constraints = {
  audio: true,
  video: { width: 1280, height: 720 },
};

navigator.mediaDevices
  .getUserMedia(constraints)
  .then((mediaStream) => {
    const video = document.querySelector("video");
    video.srcObject = mediaStream;
    video.onloadedmetadata = () => {
      video.play();
    };
  })
  .catch((err) => {
    // always check for errors at the end.
    console.error(`${err.name}: ${err.message}`);
  });
js
const constraints = {
  video: { frameRate: { ideal: 10, max: 15 } },
};
js
let front = false;
document.getElementById("flip-button").onclick = () => {
  front = !front;
};

const constraints = {
  video: { facingMode: front ? "user" : "environment" },
};