媒体设备
最后更新于:2022-04-02 03:29:54
[TOC]
> [MDN](https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices#%E4%BA%8B%E4%BB%B6)
## mediaDevices 接口
```
getDisplayMedia 获取桌面共享
getUserMedia 获取用户设备(摄像头,麦克风)
enumerateDevices 列出支持的设备
```
## 实例
### 打开某个媒体
```
const constraints = {
'video': true,
'audio': true
}
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
console.log('Got MediaStream:', stream);
})
.catch(error => {
console.error('Error accessing media devices.', error);
});
```
### 查询媒体设备
```
function getConnectedDevices(type, callback) {
navigator.mediaDevices.enumerateDevices()
.then(devices => {
const filtered = devices.filter(device => device.kind === type);
callback(filtered);
});
}
getConnectedDevices('videoinput', cameras => console.log('Cameras found', cameras));
//每个列表输出的格式
// deviceId: "default"
// groupId: "9933505448f1ebf66aebb888662edb73aac5ee39cea1e81e3d04e15e451b355b"
// kind: "audioinput"
// label: "默认 - 麦克风 (HD video ) (1903:8328)"
```
### 监听媒体变动
```
navigator.mediaDevices.addEventListener("devicechange",event=>{
console.log(event);
/**
* bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: MediaDevices {ondevicechange: null}
defaultPrevented: false
eventPhase: 0
isTrusted: true
path: []
returnValue: true
srcElement: MediaDevices {ondevicechange: null}
target: MediaDevices {ondevicechange: null}
timeStamp: 8889.65999998618
type: "devicechange"
*/
})
```
### 媒体限制
```
const constraints = {
'audio': {'echoCancellation': true},
'video': {
'deviceId': cameraId,
'width': {'min': minWidth},
'height': {'min': minHeight}
}
}
navigator.mediaDevices.getUserMedia(constraints);
```
### 本地播放
```
```
';