gpt4 book ai didi

javascript - 使用 MediaDevices.enumerateDevices() 观察变化

转载 作者:行者123 更新时间:2023-11-30 20:27:48 29 4
gpt4 key购买 nike

我目前有一个连续轮询 MediaDevices.enumerateDevices() 的方法,它会返回一组已连接的媒体设备。

let devices = [];

function getDevices() {
return new Promise(async (resolve, reject) => {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
resolve(devices);
} catch (err) {
reject(err);
}
});
}

async function listenForDeviceChanges() {
devices = await getDevices();
setTimeout(listenForDeviceChanges, 500);
}


(async () => {
await listenForDeviceChanges();
})();

这看起来效率不高,所以我想知道在 MediaDevices API 中是否有另一种方法可以做到这一点?特别是某种“观察者”方法。

最佳答案

是的,有devicechange事件:

This happens whenever the set of media devices available to the user agent and, by extension, to the web site or app has changed

https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/ondevicechange

例如

navigator.mediaDevices.ondevicechange = async function(event) {
devices = await getDevices();
};

关于javascript - 使用 MediaDevices.enumerateDevices() 观察变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50694257/

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