Maulik Soni Maulik Soni - 4 months ago 18
Javascript Question

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

Here is my code.

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


Here, when video constraint is not yet allowed by user, but audio is already allowed (due to other just audio recordings), and when prompted for the same, and user 'closes' the prompt, successCallback is called, and I won't be getting the VideoStream, but just Audio.

How can I make sure that both the video and audio permissions are allowed when successCallback is called?

jib jib
Answer

This is actually a bug in Chrome and Firefox, as it should call the errorCallback in this case. It's been fixed in Firefox Developer Edition (49).

As a workaround, check that you got two tracks:

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

A polyfill might look something like this (use https fiddle in Chrome):

let getUserMedia = c => navigator.mediaDevices.getUserMedia(c)
  .then(stream => {
    if (Object.keys(c).filter(key => c[key]).length !=
        stream.getTracks().length) {
      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>