Why is WebRTC remote video source generated by URL.createObjectURL

前端 未结 2 1489
悲哀的现实
悲哀的现实 2020-12-19 23:11

In this document, it uses URL.createObjectURL to set the video source. (This is the code to answer a call).

var offer = getOfferFromFriend();
na         


        
相关标签:
2条回答
  • 2020-12-19 23:15

    Because a WebRTC connection involves several steps and what you get from such a connection is a stream. But the src property of the video tag does not accept a stream, but a URL. And this is the way to "convert" a stream to a URL.

    0 讨论(0)
  • 2020-12-19 23:21

    URL.createObjectURL(stream) is a hack. Stop using it. Efforts are underway to remove it.

    Use video.srcObject = stream directly instead. It is standard and well-implemented.

    This assignment of a local resource should never have been a URL in the first place, and is a red herring to understanding how WebRTC works.

    WebRTC is a transmission API, sending data directly from one peer to another. No content URLs are involved. The remote stream you get from onaddstream is a local object receiver side, and is the live streaming result of the transmission, ready to be played.

    The documentation you read is old and outdated. Thanks for pointing it out, I'll fix it. It has other problems: you should call setRemoteDescription immediately, not wait for the receiver to share their camera, otherwise incoming candidates are missed. Instead of the code you show, do this:

    pc.onaddstream = e => video.srcObject = e.stream;
    
    function getOfferFromFriend(offer) {
      return pc.setRemoteDescription(new RTCSessionDescription(offer))
        .then(() => navigator.getUserMedia({video: true}))
        .then(stream => {
          pc.addStream(stream);
          return pc.createAnswer();
        })
        .then(answer => pc.setLocalDescription(answer))
        .then(() => {
          // send the answer to a server to be forwarded back to the caller (you)
        })
        .catch(error);
    }
    

    It uses srcObject, avoids the deprecated callback API, and won't cause intermittent ICE failures.

    0 讨论(0)
提交回复
热议问题