MediaDevices

MediaDevices介面可以存取連接的媒體輸入設備,像是相機、麥克風,以及螢幕分享。它可以存取任何硬體資源的媒體數據。

EventTarget MediaDevices

屬性

繼承父類EventTarget的屬性。

方法

繼承父類EventTarget的方法。

enumerateDevices()

取得一系列關於系統中可用的媒體輸入和媒體輸出設備的資訊。

getSupportedConstraints() (en-US)

返回一個符合 MediaTrackSupportedConstraints (en-US) 的物件,該物件標示出 MediaStreamTrack (en-US) 介面支援哪些可約束的屬性。請參考 Media Streams API (en-US) 瞭解更多關於 constraints 的資訊。

getDisplayMedia() (en-US)

出現提示視窗讓使用者選擇要捕捉整個螢幕或是部分(例如一個視窗)的畫面做為MediaStream (en-US),用於分享或錄製。返回值為一個解析為MediaStream 的 promise。

getUserMedia() (en-US)

透過提示視窗獲得使用者的許可後,打開系統上的相機和/或麥克風麥克風,並返回一包含視訊輸入軌道和/或音訊輸入軌道的MediaStream (en-US)

selectAudioOutput() (en-US)

出現提示視窗讓使用者選擇特定的音訊輸出設備。

事件

devicechange (en-US)

在媒體輸入或媒體輸出設備連接上使用者的系統裝置,或是從使用者的系統裝置移除時觸發。

範例

'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.onremovetrack = 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.height.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

參見