WebRTC - Change device/camera in realtime

2019-02-22 11:18发布

问题:

I'm having a problem trying to change my camera in real time, It works for the local video, but the remote person cannot see the new camera, and still sees the old one. I tried to stop the stream and init again but still not working. This is just some of my code. I have searched everywhere and I can't find a solution. Can someone help me out?

function init() {
        getUserMedia(constraints, connect, fail);
}

$(".webcam-devices").on('change', function() {
    var deviceID = this.value;
    constraints.video = {
        optional: [{
            sourceId: deviceID
        }]
    };
    stream.getTracks().forEach(function (track) { track.stop(); });
    init();
});

回答1:

You need to actually change the track you're sending in the PeerConnection. In Firefox, you can use RTPSender.replaceTrack(new_track); to change without renegotiation (this is being added to the spec now). Otherwise, you need to add the new stream/track to the RTCPeerConnection, and remove the old one, and then process the onnegotiationneeded event and renegotatiate

See one of @jib's fiddles: Jib's replaceTrack() fiddle:

function flip() {
  flipped = 1 - flipped;
  return pc1.getSenders()[0].replaceTrack(streams[flipped].getVideoTracks()[0])
  .then(() => log("Flip! (notice change in dimensions & framerate!)"))
  .catch(failed);
}