[英]WebRTC pause and resume stream
我正在嘗試使用 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 在這種靜音狀態下基本停止發送數據包,因此它非常高效。
您應該嘗試使用重新協商,我相信在 chrome 和 firefox 中的處理方式仍然存在差異:
在 Chrome 中,您只需在PeerConnection
對象上調用addStream
或removeStream
來添加/刪除流,然后創建和交換sdp
。
在firefox中,沒有直接的removeStream
,需要使用RTCRtpSender和addTrack
和removeTrack
方法,可以看看這個問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.