getUserMedia-如果用户别无选择该怎么办? [英] getUserMedia - what if user makes no choice?

查看:214
本文介绍了getUserMedia-如果用户别无选择该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我改编了一个库,可以通过用户的麦克风录制MP3音频.如果用户允许或拒绝麦克风访问请求,我很好,但是我注意到 MDN这样说:

I've adapted a library to record MP3 audio via the user's microphone. If the user allows or rejects the microphone access request, I'm fine, but I note that MDN says this:

请注意,返回的承诺可能无法解决 也不拒绝,因为不需要用户进行选择.

Note that it is possible for the returned promise to neither resolve nor reject, as the user is not required to make a choice.

但是它似乎并没有说什么,如果有的话,我确实可以捕捉到没有选择"的动作.如果用户只是退出对话框,或者在没有做出选择的情况下模糊了对话框,我是否可以捕捉到该对话框并相应地调整我的UI?

But it doesn't seem to say what, if anything, I can do catch that "no choice made" action. If the user merely quits the dialog, or blurs out of it without making a choice, can I catch that and adjust my UI accordingly?

这是我当前的代码:

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);
});

推荐答案

您可以对自己的承诺实施超时.

You could implement a timeout on the promise you have.

例如,您可以按如下所示扩展Promise对象和原型:

For instance, you could extend the Promise object and prototype as follows:

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)链接起来:

Once you have that, you can just chain in a .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);
});

这篇关于getUserMedia-如果用户别无选择该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆