How to resolve iOS 11 Safari getUserMedia “Invalid constraint” issue

北城余情 提交于 2019-11-30 08:36:54

The invalid constraint error in safari is because the browser expects that you pass a correct width, one of:

  • 320
  • 640
  • 1280

the height is auto calculate in an aspect ratio of 4:3 for 320 or 640, and 16:9 for 1280, then if you pass a width of 320, you video stream is set in:

  • 320x240

if you set a width of 640, you video stream is set in:

  • 640x480

And if you set a width of 1280, then you video stream is set in:

  • 1280x720

In any other case you got a error "InvalidConstrain" for width value.

Also you can use a min, max, exact or ideal constrains for width, please check the MDN documentation

Here an example in this codepen

var config = { video: { width: 320/*320-640-1280*/ } };
var start = () => navigator.mediaDevices.getUserMedia(config)
  .then(stream => v.srcObject = stream)
  .then(() => new Promise(resolve => v.onloadedmetadata = resolve))
  .then(() => log("Success: " + v.videoWidth + "x" + v.videoHeight))
  .catch(log);

var log = msg => div.innerHTML += "<p>" + msg + "</p>";

PD: In chrome you can set a width of height and the video stream is set in these sizes, Firefox do a fitness distance, and Safari expect a exact match.

It appears to have been a bug that was corrected, because I just tried it again and the error message no longer appears.

Note that while the error message went away, I did have to make one more change for it to work, which was adding video.srcObject = stream; in the then callback.

Remember that the iOS Simulator that comes with Xcode does not support webcam or microphone, which is why you may get the OverconstrainedError (as per https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia docs, that means no device fits the passed options, even if you're not putting specifics)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!