You need first to enumerate the number of cameras and save them in a var like this:
var camcounter; // camera counter
var camera_id = {}; // array of cameras by device id
navigator.mediaDevices.enumerateDevices()
.then(function(myStream) {
myStream.forEach(function(myStream) {
if(myStream.kind === 'videoinput') {
camcounter++; //camera count
camera_id.push(myStream.deviceId); //pushing the device ID to the array
console.log(myStream.kind + ": " + myStream.label + " id = " + myStream.deviceId);
}
});
})
.then(function(myStream) {
if(camcounter === 1) { //building mediaContraints if just one camera found
console.log('one camera profile');
mediaConstraints = {
video: {deviceId: {exact: camera_id[0]}},
audio: {mandatory: {echoCancellation: true, googAutoGainControl: true, googNoiseSuppression: true, googHighpassFilter: true, googTypingNoiseDetection: true}}
};
}
else {
if(camcounter === 2) { //building mediaContraints if two cameras found
mediaConstraints = {
video: {deviceId: {exact: camera_id[1]}},
audio: {mandatory: {echoCancellation: true, googAutoGainControl: true, googNoiseSuppression: true, googHighpassFilter: true, googTypingNoiseDetection: true}}
};
}
else {
console.log('no camera or more than 2 cameras');
}
}
})
.then(function(myStream) {
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then(function(myStream) {
stream = myStream;
usercam1.srcObject = stream;
pc = new PeerConnection(servers);
pc.addStream(stream);
pc.ontrack = function(e) {
usercam2.srcObject = e.streams[0];
};
pc.onicecandidate = function(event) {
if(event.candidate) {
send({type: 'candidate', candidate: event.candidate});
}
};
})
})
.catch(function(error) {
console.log('error switching camera :' + error + ' camecounter is: ' + camcounter);
});