It is possible to set "hints" for the preferred cam/resolution during video capture. This is done by using a "constraint" object that is passed as a parameter to the getUserMedia(...) method. It's just the same object we passed in the basic example: navigator.getUserMedia({video:true}, success, error) except that this time this object is a little more complex by including new properties in addition to video:true or audio:true.
For more information, this article on MDN about the getUserMedia API gives great examples on how to set the camera resolution and/or to choose the front or back camera when using a mobile phone.
Typical use:
Code source extract related to the "constraint" object which specifies the desired resolutions:
var vgaConstraints = {
video: {
width: { max: 640 },
height: { max: 360 }
}
};
var hdConstraints = {
video: {
width: { min: 1280 },
height: { min: 720 }
}
};
let constraints = hdConstraints;
navigator.mediaDevices.getUserMedia(constraints)
.then((stream) => {...}
Use this Web app that systematically tests a set of "preferred resolutions" and compares them to the actual resolutions returned by the browser. Remember that the requested resolution is a hint, and there is no real guarantee that your configuration will allow it.
Here are some other constraints you can set. In particular, look at the ones for selecting the front or rear camera (smartphones):
// more on video resolution
constraints = {
video: {
width: { min: 1024, ideal: 1280, max: 1920 },
height: { min: 776, ideal: 720, max: 1080 }
}
}
// Framerate
constraints = { video: { frameRate: { ideal: 10, max: 15 } } };
// front and back camera (mobile), some examples
var front = false;
document.getElementById('flip-button').onclick = function() {
front = !front;
};
// toggle front and back camera (mobile) by clicking a button
constraints = { video: { facingMode: (front? "user" : "environment") } };
// prefer front camera
constraints = { audio: true, video: { facingMode: "user" } }
// require rear camera
constraints = { audio: true, video: { facingMode: { exact: "environment" } } }
Resource: WebRTC samples: Select sources & outputs
Source code extract:
function gotDevices(deviceInfos) {
for (var i = 0; i !== deviceInfos.length; ++i) {
var deviceInfo = deviceInfos[i];
console.log("device with id: " + deviceInfo.deviceId);
// possible values: audioinput, audiooutput, videoinput
console.log("device with kind: " + deviceInfo.kind);
// 'speaker' or 'camera' for example
console.log("device with label: " + deviceInfo.label);
//... should build a menu, test kind/label and set
// audioSource and videoSource variables
}
}
// ...
var constraints = {
audio: {deviceId: audioSource ? {exact: audioSource} : undefined},
video: {deviceId: videoSource ? {exact: videoSource} : undefined}
};
navigator.mediaDevices.getUserMedia(constraints).
then(gotStream).then(gotDevices).catch(handleError)