aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/mediadevices/ondevicechange/index.html
blob: 4c9c9cb0e0f65e645cfba529297bce2b95cce1da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
---
title: MediaDevices.ondevicechange
slug: Web/API/MediaDevices/ondevicechange
translation_of: Web/API/MediaDevices/ondevicechange
---
<p>{{APIRef("Media Capture and Streams")}}</p>

<p><span class="seoSummary"> <strong><code>MediaDevices.ondevicechange</code></strong> 属性是一种{{domxref("EventHandler")}},当{{domxref("MediaDevices")}} 接口的{{event("devicechange")}}事件被触发时会被调用. 不论{{Glossary("user agent")}}媒体设备的设置是否可用, 或者网站或者应用发生变了都会触发。无论何时你都可以使用 {{domxref("MediaDevices.enumerateDevices", "enumerateDevices()")}}  去更新可用设备列表.</span></p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox"><em>MediaDevices</em>.ondevicechange = <em>eventHandler</em>;
</pre>

<h3 id="Value">Value</h3>

<p>A function you provide which accepts as input a {{domxref("Event")}} object describing the {{domxref("devicehange")}} 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 {{domxref("MediaDevices.enumerateDevices", "enumerateDevices()")}}.</p>

<h2 id="Example" name="Example">Example</h2>

<p>In this example, we create a function called <code>updateDeviceList()</code>, which is called once when {{domxref("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 {{event("devicechange")}} event, the list is refreshed any time a media device is attached to or removed from the device running the sample.</p>

<div class="hidden">
<h3 id="HTML_content">HTML content</h3>

<pre class="brush: html">&lt;p&gt;Click the start button below to begin the demonstration.&lt;/p&gt;
&lt;div id="startButton" class="button"&gt;
  Start
&lt;/div&gt;
&lt;video id="video" width="160" height="120" autoplay&gt;&lt;/video&gt;&lt;br&gt;

&lt;div class="left"&gt;
  &lt;h2&gt;Audio devices:&lt;/h2&gt;
  &lt;ul class="deviceList" id="audioList"&gt;&lt;/ul&gt;
&lt;/div&gt;
&lt;div class="right"&gt;
  &lt;h2&gt;Video devices:&lt;/h2&gt;
  &lt;ul class="deviceList" id="videoList"&gt;&lt;/ul&gt;
&lt;/div&gt;

&lt;div id="log"&gt;&lt;/div&gt;</pre>

<h3 id="CSS_content">CSS content</h3>

<pre class="brush: css">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;
}</pre>

<h3 id="JavaScript_content">JavaScript content</h3>

<h4 id="Other_code">Other code</h4>

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

<pre class="brush: js">let videoElement = document.getElementById("video");
let logElement = document.getElementById("log");

function log(msg) {
  logElement.innerHTML += msg + "&lt;br&gt;";
}

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 =&gt; {
      videoElement.srcObject = stream;
      updateDeviceList();
    })
    .catch(err =&gt; log(err.name + ": " + err.message));
}, false);</pre>
</div>

<p>We set up global variables that contain references to the {{HTMLElement("ul")}} elements that are used to list the audio and video devices:</p>

<pre class="brush: js">let audioList = document.getElementById("audioList");
let videoList = document.getElementById("videoList");</pre>

<h4 id="Getting_and_drawing_the_device_list">Getting and drawing the device list</h4>

<p>Now let's take a look at <code>updateDeviceList()</code> 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.</p>

<pre class="brush: js">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 = "&lt;strong&gt;" + device.label + "&lt;/strong&gt; (" + direction + ")";
      if (type === "audio") {
        audioList.appendChild(elem);
      } else if (type === "video") {
        videoList.appendChild(elem);
      }
    });
  });
}</pre>

<p><code>updateDeviceList()</code> consists entirely of a call to the function {{domxref("MediaDevices.enumerateDevices", "enumerateDevices()")}} on the {{domxref("MediaDevices")}} object referenced in the {{domxref("navigator.mediaDevices")}} property, as well as the code that's run when the {{jsxref("promise")}} returned by <code>enumerateDevices()</code> 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 {{domxref("MediaDeviceInfo")}} objects, each describing one media input or output device.</p>

<p>A {{jsxref("Array.forEach", "forEach()")}} loop is used to scan through all the devices. For each device, we create a new {{HTMLElement("li")}} object to be used to display it to the user.</p>

<p>The line <code>let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i);</code> deserves special notice. This uses <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructuring assignment</a> (a new feature of <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla">ECMAScript 6</a>) to assign the values of the first three items in the array returned by {{jsxref("String.match()")}} to the variables <code>kind</code>, <code>type</code>, and <code>direction</code>. We do this because the value of {{domxref("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.</p>

<p>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 {{domxref("Node.appendChild", "appendChild()")}} on either <code>audioList</code> or <code>videoList</code>, as appropriate based on the device type.</p>

<h4 id="Handling_device_list_changes">Handling device list changes</h4>

<p>We call <code>updateDeviceList()</code> in two places. The first is in the {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} promise's fulfillment handler, to initially fill out the list when the stream is opened. The second is in the event handler for {{event("devicechange")}}:</p>

<pre class="brush: js">navigator.mediaDevices.ondevicechange = function(event) {
  updateDeviceList();
}</pre>

<p>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 <code>updateDeviceList()</code> to redraw the list of connected devices.</p>

<h3 id="Result">Result</h3>

<p>{{ EmbedLiveSample('Example', 600, 460) }}</p>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{ SpecName('Media Capture', '#dom-mediadevices-ondevicechange', 'ondevicechange') }}</td>
   <td>{{ Spec2('Media Capture') }}</td>
   <td>Initial specification.</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari (WebKit)</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatChrome(57)}}</td>
   <td>{{CompatGeckoDesktop(51)}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatOpera(34)}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android Webview</th>
   <th>Chrome for Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Phone</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatOperaMobile(34)}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<p>[1] Support for the <code>devicechange</code> event and for {{domxref("MediaDevices.ondevicechange")}} landed in Firefox 51, but <em>only for Mac</em>, and disabled by default. It can be enabled by setting the preference <code>media.ondevicechange.enabled</code> to <code>true</code>. Support for this event was added for Linux and Windows—and it was enabled by default—starting in Firefox 52.</p>

<h2 id="See_also">See also</h2>

<ul>
 <li>The {{event("devicechange")}} event and its type, {{domxref("Event")}}.</li>
 <li>{{domxref("MediaDevices.enumerateDevices()")}}</li>
 <li>{{domxref("MediaDeviceInfo")}}</li>
</ul>