gpt4 book ai didi

javascript - getUserMedia : how to find the active devices? 后的 enumerateDevices

转载 作者:行者123 更新时间:2023-12-03 23:40:35 25 4
gpt4 key购买 nike

给定 MediaStream,有没有办法检测哪个设备(相机、麦克风)处于事件状态?实例?
我目前正在开发的应用程序只是简单地查询这样的流并将其附加到 <video/>元素:

const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true })

const el = document.querySelector("video")
el.srcObject = stream

console.log(stream.getTracks())
// MediaStreamTrack { kind: "audio", id: "{000d071e-f936-42d8-872e-a568cd96cc2d}", label: "USB Audio Device Mono", … }
​// MediaStreamTrack { kind: "video", id: "{186427d5-b04a-4906-9177-1a088c5d4e0a}", label: "C922 Pro Stream Webcam", …
下一步是让用户能够更改摄像头/麦克风。基本代码是:
const devices = await navigator.mediaDevices.enumerateDevices()
console.log(devices)
// MediaDeviceInfo { deviceId: "yQx5+MN7znbmkE0tV98jJHpvqrUaa6Gv5WIXF52jj0s=", kind: "videoinput", label: "C922 Pro Stream Webcam", … }
​// MediaDeviceInfo { deviceId: "dIjwtaOGQbjT2HOqfJ4xjzjXBwBxz4CEeX3a2fn0ZgA=", kind: "audioinput", label: "USB Audio Device Mono", … }​
// MediaDeviceInfo { deviceId: "/t3u7BlfExATtBC4CUmyqIo8RORDxMu9aMrJJHN0Ez0=", kind: "audioinput", label: "C922 Pro Stream Webcam Analog Stereo", … }​
// MediaDeviceInfo { deviceId: "/5pqK1599b+mKHm26zCYQ+Ql3vG0Em7xiVbqfm1C/9A=", kind: "audioinput", label: "Monitor of Built-in Audio Digital Stereo (IEC958)", … }
// MediaDeviceInfo { deviceId: "Tib/PVScFuFUQuAtYYVgtxcxeu08opGKe9MXEVmxq84=", kind: "audioinput", label: "Monitor of USB Audio Device Analog Stereo", … }
我可以简单地将这个列表转换为 <select/> + <option/>列表(每个 kind 一个),让用户决定并重新请求所选 deviceId 的流( getUserMedia({ audio: { deviceId: selectedDeviceId } }))。
但是:轨道和设备 ID 不匹配,如何确定 <option/>应该预选吗?查看 MDN,stream 的 track ID 是 generated by the browser (这是有道理的),但是 MediaStream API没有提供太多选择...
当然,答案不能是“按标签行事”——我可以插入第二个相同的网络摄像头并拥有两个同名的视频设备?

最佳答案

你可以得到MediaTrackSettings当前应用于您的 MediaStreamTracks 并检查 deviceId从那里:

const used_devices = mediastream.getTracks()
.map( (track) => track.getSettings().deviceId );

关于javascript - getUserMedia : how to find the active devices? 后的 enumerateDevices,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66048083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com