我正在尝试使用WebRTC来构建一个Web应用程序,当某些事件触发时,需要暂停/恢复视频/音频流.我试过了getTracks()[0] .stop(),但我不知道如何恢复流.
解决方法
getTracks()[0] .stop()是永久的.
请改用getTracks()[0] .enabled = false.要取消暂停getTracks()[0] .enabled = true.
这将用黑色代替你的视频,用沉默代替你的音频.
试试吧(使用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 += "<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基本上停止在此静音状态下发送数据包,因此它非常高效.