MediaDevices.ondevicechange property is an EventHandler which specifies a function to be called when the devicechange event occurs on a MediaDevices instance. This happens whenever the set of media devices available to the 用户代理 and, by extension, to the web site or app has changed. You can at any time use enumerateDevices() to get the updated list of available devices.

句法

MediaDevices.ondevicechange = eventHandler;
					

A function you provide which accepts as input a 事件 object describing the devicechange event that occurred. There is no information about the change included in the event object; to get the updated list of devices, you'll have to use enumerateDevices() .

范例

In this example, we create a function called updateDeviceList() , which is called once when MediaDevices.getUserMedia() successfully obtains a stream, and then is called any time the device list changes. It displays in the browser window two lists: one of audio devices and one of video devices, with both the device's label (name) and whether it's an input or an output device. Because the example provides a handler for the devicechange event, the list is refreshed any time a media device is attached to or removed from the device running the sample.

HTML 内容

<p>Click the start button below to begin the demonstration.</p>
<div id="startButton" class="button">
  开始
</div>
<video id="video" width="160" height="120" autoplay></video><br>
<div class="left">
  <h2>Audio devices:</h2>
  <ul class="deviceList" id="audioList"></ul>
</div>
<div class="right">
  <h2>Video devices:</h2>
  <ul class="deviceList" id="videoList"></ul>
</div>
<div id="log"></div>
					

CSS content

body {
  font: 14px "Open Sans", "Arial", sans-serif;
}
video {
  margin-top: 20px;
  border: 1px solid black;
}
.button {
  cursor: pointer;
  width: 160px;
  border: 1px solid black;
  font-size: 16px;
  text-align: center;
  padding-top: 2px;
  padding-bottom: 4px;
  color: white;
  background-color: darkgreen;
}
h2 {
  margin-bottom: 4px;
}
.left {
  float:left;
  width: 48%;
  margin-right: 2%
}
.right {
  float:right;
  width: 48%;
  margin-left: 2%
}
.deviceList {
  border: 1px solid black;
  list-style-type: none;
  margin-top: 2px;
  padding: 6px;
}
					

JavaScript 内容

Other code

Below is other code which, while needed to make this example work, isn'tt related directly to ondevicechange , so we won't go into any detail.

let videoElement = document.getElementById("video");
let logElement = document.getElementById("log");
function log(msg) {
  logElement.innerHTML += msg + "<br>";
}
document.getElementById("startButton").addEventListener("click", function() {
  navigator.mediaDevices.getUserMedia({
    video: {
      width: 160,
      height: 120,
      frameRate: 30
    },
    audio: {
      sampleRate: 44100,
      sampleSize: 16,
      volume: 0.25
    }
  }).then(stream => {
      videoElement.srcObject = stream;
      updateDeviceList();
    })
    .catch(err => log(err.name + ": " + err.message));
}, false);
					

We set up global variables that contain references to the <ul> elements that are used to list the audio and video devices:

let audioList = document.getElementById("audioList");
let videoList = document.getElementById("videoList");
					

Getting and drawing the device list

Now let's take a look at updateDeviceList() itself. This method is called any time we want to fetch the current list of media devices and then update the displayed lists of audo and video devices using that information.

function updateDeviceList() {
  navigator.mediaDevices.enumerateDevices()
  .then(function(devices) {
    audioList.innerHTML = "";
    videoList.innerHTML = "";
    devices.forEach(function(device) {
      let elem = document.createElement("li");
      let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i);
      elem.innerHTML = "<strong>" + device.label + "</strong> (" + direction + ")";
      if (type === "audio") {
        audioList.appendChild(elem);
      } else if (type === "video") {
        videoList.appendChild(elem);
      }
    });
  });
}
					

updateDeviceList() consists entirely of a call to the function enumerateDevices() MediaDevices object referenced in the navigator.mediaDevices property, as well as the code that's run when the promise 返回通过 enumerateDevices() is fulfilled. The fulfillment handler is called when the device list is ready. The list is passed into the fulfillment handler as an array of MediaDeviceInfo objects, each describing one media input or output device.

A forEach() loop is used to scan through all the devices. For each device, we create a new <li> object to be used to display it to the user.

The line let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i); deserves special notice. This uses 析构赋值 (a new feature of ECMAScript 6 ) to assign the values of the first three items in the array returned by String.match() to the variables kind , type ,和 direction . We do this because the value of MediaDeviceInfo.kind is a single string that includes both the media type and the direction the media flows, such as "audioinput" or "videooutput". This line, then, pulls out the type ("audio" or "video") and direction ("input" or "output") so they can be used to construct the string displayed in the list.

Once the string is assembled, containing the device's name in bold and the direction in parentheses, it's appended to the appropriate list by calling appendChild() on either audioList or videoList , as appropriate based on the device type.

Handling device list changes

调用 updateDeviceList() in two places. The first is in the getUserMedia() promise's fulfillment handler, to initially fill out the list when the stream is opened. The second is in the event handler for devicechange :

navigator.mediaDevices.ondevicechange = function(event) {
  updateDeviceList();
}
					

With this code in place, each time the user plugs in a camera, microphone, or other media device, or turns one on or off, we call updateDeviceList() to redraw the list of connected devices.

结果

规范

规范 状态 注释
媒体捕获和流
The definition of 'ondevicechange' in that specification.
候选推荐 最初的规范。

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
ondevicechange Chrome 57 Edge 12 Firefox 52
52
51 — 52 注意事项 Disabled
MediaDevices.ondevicechange is supported only on macOS.
Disabled ). To change preferences in Firefox, visit about:config.
IE 不支持 No Opera 34 Safari 不支持 No WebView Android 不支持 No Chrome Android 不支持 No Firefox Android Yes Opera Android 34 Safari iOS 不支持 No Samsung Internet Android 不支持 No

图例

完整支持

完整支持

不支持

不支持

见实现注意事项。

用户必须明确启用此特征。

用户必须明确启用此特征。

另请参阅

元数据

  • 最后修改: