我已经改编了一个库来通过用户的麦克风录制MP3音频。如果用户允许或拒绝麦克风访问请求,我很好,但我注意到MDN says这个:
请注意,返回的promise可能无法解析 也不拒绝,因为用户不需要做出选择。
但似乎并没有说出什么,如果有的话,我可以抓住那个“别无选择”的行动。如果用户只是退出对话框,或者在没有做出选择的情况下模糊了它,我可以抓住它并相应地调整我的UI吗?
这是我目前的代码:
navigator.mediaDevices.getUserMedia({audio: true}).then(function(stream) {
build_ui();
startUserMedia(stream);
}).catch(function(e) { //<-- doesn't fire if no choice made
cfg.no_device_callback && cfg.no_device_callback(e);
});
答案 0 :(得分:1)
您可以对您的承诺实施超时。
例如,您可以按如下方式扩展Promise对象和原型:
Promise.wait = function (ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms);
});
};
Promise.prototype.timeout = function(ms) {
return Promise.race([
this,
Promise.wait(ms).then(function () {
throw new Error("time out");
})
])
};
一旦你拥有了这个,你就可以链接到.timeout(10000)
:
navigator.mediaDevices.getUserMedia({audio: true})
.timeout(10000).then(function(stream) {
// ^^^^^^^^^^^^^^^
build_ui();
startUserMedia(stream);
}).catch(function(e) { //<-- now also fires if no choice made within 10 secs
cfg.no_device_callback && cfg.no_device_callback(e);
});