I can't figure this out properly, or if it's even possible to switch cameras.
I've tried stopping the video track before calling getUserMedia a second time, hoping that stopping the video track would turn the front camera off so the rear camera can turn on, but it just doesn't work.
var oldStream; // the old stream from getUserMedia
Function SwitchCamera() {
oldStream.getVideoTracks()[0].stop();
navigator.mediaDevices.getUserMedia({audio: true, video: {deviceId: 'rear camera device ID'}).then(function(newStream){
// this never runs
}).catch(function(err){
console.log(err); // Cannot connect camera
});
}
Is there something else that I need to do to switch cameras on mobile? Is this even possible?
On mobile, it appears we just need to give the camera enough time to shut down. Wrapping getUserMedia
in a setTimeout
with a delay of about 1 second (1,000 ms) is sufficient for my testing, though I'm also going to attempt to swap the camera 3 times consecutively before throwing an error. I'm not sure how, or even if it's possible, to check if the actual device is stopped or turned off, but I suspect that's impossible due to browser security.
In a perfect world MediaStreamTrack.stop()
would return a promise that gives us information about whether the device associated with the track is actually stopped/off or if it is still running due to it being used in other tracks.