navigator.getUserMedia 允许一个约束,另一个不允许,关闭浏览器提示时调用成功回调

navigator.getUserMedia one constraint allowed, another one not, success callback called upon closing browser prompt

这是我的代码。

captureUserMedia(mediaConstraints, successCallback, errorCallback) {
    navigator.getUserMedia(mediaConstraints, successCallback, errorCallback);
}

captureUserMedia00(callback){
  captureUserMedia({
    audio: true,
    video: true
  }, function(stream) {
    console.log('user media Callback', stream);
    callback(stream);
  }, function(error) {
    console.log('user media Error ', JSON.stringify(error));
  });
 }});
}

此处,当用户尚未允许视频约束,但已经允许音频(由于其他只是录音)时,当提示相同且用户 'closes' 提示时,successCallback 是调用,我不会得到 VideoStream,只有音频。

调用successCallback时如何确保视频和音频权限都被允许?

这实际上是 Chrome 和 Firefox 中的错误,因为它 should 在这种情况下调用 errorCallback。它已在 Firefox Developer Edition (49) 中修复。

解决方法是检查您是否有两个曲目:

if (stream.getTracks().length < 2) {
  throw new Error("Need both");
}

polyfill 可能看起来像这样(在 Chrome 中使用 https fiddle):

let getUserMedia = constraints =>
  navigator.mediaDevices.getUserMedia(constraints).then(stream => {
    if (constraints.audio && !stream.getAudioTracks().length ||
        constraints.video && !stream.getVideoTracks().length) {
      stream.getTracks().forEach(track => track.stop());
      throw new DOMException("The object can not be found here.",
                             "NotFoundError");
    }
    return stream;
  });

getUserMedia({ video: true, audio: true })
  .then(stream => video.srcObject = stream)
  .catch(e => console.log(e.name + ": "+ e.message));
<video id="video" width="160" height="120" autoplay></video>