How to switch cameras in PWA app built with reactjs?
edit: to make the camera list enumerate on page load, you need to ask for permissions right away:
window.onload = function(){ navigator.getUserMedia({audio:true,video:true}, function(stream) { stream.getTracks().forEach(x=>x.stop()); getCamAndMics(); }, err=>console.log(err));<rest of app>}
I have built an app that enumerates through the cameras available, and then lets the user choose which camera to record with:
function getCamAndMics(){ // List cameras and microphones. in the menu navigator.mediaDevices.enumerateDevices() .then(function(devices) { devices.forEach(function(device) { console.log(device.kind + ": " + device.label +" id = " + device.deviceId); var audioSelect = document.getElementById("audioPicker-select"); var cameraSelect = document.getElementById("cameraPicker-select"); if(device.kind=="audioinput"){ //add a select to the audio dropdown list var option = document.createElement("option"); option.value = device.deviceId; option.text = device.label; audioSelect.appendChild(option); }else if(device.kind =="videoinput"){ //add a select to the camera dropdown list var option = document.createElement("option"); option.value = device.deviceId; option.text = device.label; cameraSelect.appendChild(option); } }); }) .catch(function(err) { console.log(err.name + ": " + err.message); });}
Even while the recording is underway - if the user changes the value, the camera will switch. This is not only great on mobile (front & back cameras), but also for desktops that might have a few media devices connected.
I send the cameraId in the configuration to the getUserMedia:
var videoOptions = { deviceId: cameraId, width: { min: 100, ideal: cameraW, max: 1920 }, height: { min: 100, ideal: cameraH, max: 1080 }, frameRate: {ideal: cameraFR} }; cameraMediaOptions = { audio: false, video: videoOptions }; cameraStream = await navigator.mediaDevices.getUserMedia(cameraMediaOptions);
Code is on Github:https://github.com/dougsillars/recordavideo/blob/main/public/index.js
Demo is live at https://record.a.video.
With this setup, I can livestream or record and upload the video to share on demand. (The backend is https://api.video for VOD and live streaming)