When you have multiple web cameras.
You can select web camera on the chrome , setting -> contents -> media
But,I would like to select camera from script.
How can I select camera by Html5 or javascript?
Check this... It is huge code so I have not pasted it here.
This is camera API for DOM [Document Object Model]
To select the webcam you need to have 2 steps. 1ยบ step is about listing all devices:
<select id="video_id"></select>
<script>
navigator.getMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
devices.forEach(function(device) {
if (device.kind == "videoinput"){
jQuery("#video_id").append("<option value='" + device.deviceId + "'>" + device.label + "</option>");
}
});
});
</script>
Easy peasy. EnumerateDevices inside mediaDevices list all devices. I put each one using JQuery in the SELECT html. Now you have all options with all devices with the value being the ID of each device.
When someone select the device, it will trigger a function:
jQuery("#video_id").change(function(){
redo_video();
})
Above jQuery sets the trigger when the select changes. It will fire the function redo_video()
function redo_video(){
constraints = {
width: { ideal: 1280, max: 1920 },
height: {ideal: 720, max: 1080 },
deviceId: { exact: jQuery("#video_id").val() }
}
navigator.getMedia(
{
video: constraints,
audio: false
},
function(stream) {
video = document.querySelector('#video');
if (navigator.mozGetUserMedia) {
video.mozSrcObject = stream;
} else {
try {
video.srcObject = stream;
console.log(stream);
} catch (error) {
video.src = window.URL.createObjectURL(stream);
}
}
video.onloadedmetadata = function(e) {
video.play();
};
},
function(err) {
console.log("An error occured! " + err);
}
);
}
The function restarts the video player choose a device with a specific deviceId (the option selected).