WebRTC pause and resume stream

前端 未结 2 790
梦谈多话
梦谈多话 2021-02-05 08:58

I am trying to use WebRTC to build a web application that needs to pause/resume the video/audio stream when some events trigger. I have tried the getTracks()[0].stop()

2条回答
  •  执笔经年
    2021-02-05 09:38

    getTracks()[0].stop() is permanent.

    Use getTracks()[0].enabled = false instead. To unpause getTracks()[0].enabled = true.

    This will replace your video with black, and your audio with silence.

    Try it (use https fiddle for Chrome):

    var pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
    
    navigator.mediaDevices.getUserMedia({ video: true, audio: true })
      .then(stream => pc1.addStream(video1.srcObject = stream))
      .catch(log);
    
    var mute = () => video1.srcObject.getTracks().forEach(t => t.enabled = !t.enabled);
    
    var add = (pc, can) => can && pc.addIceCandidate(can).catch(log);
    pc1.onicecandidate = e => add(pc2, e.candidate);
    pc2.onicecandidate = e => add(pc1, e.candidate);
    
    pc2.onaddstream = e => video2.srcObject = e.stream;
    pc1.onnegotiationneeded = e =>
      pc1.createOffer().then(d => pc1.setLocalDescription(d))
      .then(() => pc2.setRemoteDescription(pc1.localDescription))
      .then(() => pc2.createAnswer()).then(d => pc2.setLocalDescription(d))
      .then(() => pc1.setRemoteDescription(pc2.localDescription))
      .catch(log);
    
    var log = msg => div.innerHTML += "
    " + msg;
    
    
    mute

    PeerConnections basically stop sending packets in this muted state, so it is highly efficient.

提交回复
热议问题