MediaDevices

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.

MediaDevices 接口提供访问连接媒体输入的设备,如照相机和麦克风,以及屏幕共享等。它可以使你取得任何硬件资源的媒体数据。

属性

从父类EventTarget中继承的属性。

事件

devicechange

当媒体输入或输出设备连接到用户计算机或从用户计算机移除时触发。

方法

从其父项继承方法 EventTarget

MediaDevices.enumerateDevices()

获取有关系统中可用的媒体输入和输出设备的一系列信息。

getSupportedConstraints()

返回一个符合 MediaTrackSupportedConstraints 的对象。该对象指明了 MediaStreamTrack 接口支持的可约束的属性。查看 Media Streams API 以了解更多相关信息。

getDisplayMedia()

提示用户选择显示器或显示器的一部分(例如窗口)以捕获为MediaStream 以便共享或记录。返回解析为 MediaStream 的 Promise。

MediaDevices.getUserMedia()

在用户通过提示允许的情况下,打开系统上的相机或屏幕共享和/或麦克风,并提供 MediaStream 包含视频轨道和/或音频轨道的输入。

示例

js
"use strict";

// Put variables in global scope to make them available to the browser console.
var video = document.querySelector("video");
var constraints = (window.constraints = {
  audio: false,
  video: true,
});
var errorElement = document.querySelector("#errorMsg");

navigator.mediaDevices
  .getUserMedia(constraints)
  .then(function (stream) {
    var videoTracks = stream.getVideoTracks();
    console.log("Got stream with constraints:", constraints);
    console.log("Using video device: " + videoTracks[0].label);
    stream.onended = function () {
      console.log("Stream ended");
    };
    window.stream = stream; // make variable available to browser console
    video.srcObject = stream;
  })
  .catch(function (error) {
    if (error.name === "ConstraintNotSatisfiedError") {
      errorMsg(
        "The resolution " +
          constraints.video.width.exact +
          "x" +
          constraints.video.width.exact +
          " px is not supported by your device.",
      );
    } else if (error.name === "PermissionDeniedError") {
      errorMsg(
        "Permissions have not been granted to use your camera and " +
          "microphone, you need to allow the page access to your devices in " +
          "order for the demo to work.",
      );
    }
    errorMsg("getUserMedia error: " + error.name, error);
  });

function errorMsg(msg, error) {
  errorElement.innerHTML += "<p>" + msg + "</p>";
  if (typeof error !== "undefined") {
    console.error(error);
  }
}

规范

Specification
Media Capture and Streams
# mediadevices

浏览器兼容性

BCD tables only load in the browser

参见