我正在尝试使用WebRTC来构建一个Web应用程序,该应用程序需要在某些事件触发时暂停/恢复视频/音频流。我已经尝试了getTracks()[0].stop(),但不确定如何恢复流。有什么建议吗?谢谢

最佳答案

getTracks()[0].stop()是永久的。

请改用getTracks()[0].enabled = false。取消暂停getTracks()[0].enabled = true

这会将您的视频替换为黑色,将音频替换为静音。

尝试一下(对于Chrome使用https fiddle):

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 += "<br>" + msg;
<video id="video1" height="120" width="160" autoplay muted></video>
<video id="video2" height="120" width="160" autoplay></video><br>
<input type="checkbox" onclick="mute()">mute</input><div id="div"></div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>


PeerConnections基本上会在此静音状态下停止发送数据包,因此它非常高效。

关于javascript - WebRTC暂停并恢复流,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35857576/

10-09 14:53