WebRTC: Switch camera

1,479 views
Skip to first unread message

Nizar Boukhari

unread,
Aug 24, 2016, 1:41:14 PM8/24/16
to discuss-webrtc
Hi everyone,

I want to be able to switch the camera during a WebRTC communication. I already posted in SO but im still waiting for an answer. here is the link to the post => stackoverflow

basically I get the media sources using the following command => "MediaStreamTrack.getSources", it gives me two sources (since the code is running in a mobile device) like so => 

{
    id: "id_source_1" | "id_source_2",
    facing: "user" | "environment",
    kind: "kind_1" | "kind_2",
    label: "label_1" | "label_2"
 }

then during the call the user clicks a button to switch the camera that will execute the following code => 

var mediaParams = {
       audio: true,
       video: { deviceId : source_2.id},
       options: {
           muted: true,
           mirror: true
       },
       elemId: 'localVideo'
};

callingSession.getUserMedia(mediaParams, function (error, stream) {
if (error) {
   console.error('error getting user media');
} else {
          var oldVideoTracks = callingSession.localStream.getVideoTracks();      
          var newVideoTracks = stream.getVideoTracks();

          if (oldVideoTracks.length > 0 && newVideoTracks.length > 0) {
               callingSession.localStream.removeTrack(oldVideoTracks[0]);
               callingSession.localStream.addTrack(newVideoTracks[0]);
          } 
       }
 });

apparently im doing something wrong, because the "stream" in the callback of the "getUserMedia" method is still the exact same old stream, even if the method has new constraint.

how can I switch the camera without renegociating the call, or change the video resolution or any changes that imply new constraints.

I really need to understand whats the failure in this code :(

Thank you very much.


Vincent Bian

unread,
Jul 17, 2018, 7:32:21 AM7/17/18
to discuss-webrtc
Do you find the solution of switch the camera without renegotiating the call ?

Diogo Moraes

unread,
Jul 18, 2018, 2:28:44 AM7/18/18
to discuss-webrtc
You can now use the replaceTrack method to change the tracks that are being sent without renegociating:

localStream.getTracks().forEach(function(track) {
    track.stop();
});
// after the getUserMedia with the new constraints
peerConnection.getSenders().map(sender => sender.replaceTrack(newStream.getTracks().find(t => t.kind === sender.track.kind), newStream))
Reply all
Reply to author
Forward
0 new messages