ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[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); ``` ### 本地播放 ``` <video autoplay playsinline controls="false"></video> <script> const video = document.querySelector("video") const constraints={ 'video':true, 'audio':true, } navigator.mediaDevices.getDisplayMedia(constraints) .then(stream=>{ video.srcObject=stream }).catch(err=>{ console.log(err); }) </script> ```