更新: 底部附近的工作示例。
由于规范不断发展,这在很大程度上取决于您目前使用的浏览器。
在规范和 Firefox 中,对等连接现在基本上是基于轨道的,并且不依赖于本地流关联。你有var sender = pc.addTrack(track, stream)
, pc.removeTrack(sender)
, 甚至sender.replaceTrack(track)
, 后者根本不涉及重新谈判。
在 Chrome 中,您仍然只有pc.addStream
and pc.removeStream
,并且从本地流中删除轨道会导致停止发送它,但将其添加回来不起作用。我很幸运地将整个流删除并重新添加到对等连接,然后重新协商。
不幸的是,在这里使用adapter.js并没有帮助,因为polyfilladdTrack
很棘手。
重新谈判
重新谈判不是重新开始。所有你需要的是:
pc.onnegotiationneeded = e => pc.createOffer()
.then(offer => pc.setLocalDescription(offer))
.then(() => signalingChannel.send(JSON.stringify({sdp: pc.localDescription})));
.catch(failed);
添加后,对等连接会在需要时使用您的信令通道自动重新协商。这甚至取代了createOffer
你现在正在做的电话和朋友,一个净赢。
有了这个,您可以在实时连接期间添加/删除曲目,它应该“正常工作”。
如果这还不够流畅,你甚至可以pc.createDataChannel("yourOwnSignalingChannel")
例子
这是所有这些的示例(在 Chrome 中使用https 小提琴):
var config = { iceServers: [{ urls: "stun:stun.l.google.com:19302" }] };
var signalingDelayMs = 0;
var dc, sc, pc = new RTCPeerConnection(config), live = false;
pc.onaddstream = e => v2.srcObject = e.stream;
pc.ondatachannel = e => dc? scInit(sc = e.channel) : dcInit(dc = e.channel);
var streams = [];
var haveGum = navigator.mediaDevices.getUserMedia({fake:true, video:true})
.then(stream => streams[1] = stream)
.then(() => navigator.mediaDevices.getUserMedia({ video: true }))
.then(stream => v1.srcObject = streams[0] = stream);
pc.oniceconnectionstatechange = () => update(pc.iceConnectionState);
var negotiating; // Chrome workaround
pc.onnegotiationneeded = () => {
if (negotiating) return;
negotiating = true;
pc.createOffer().then(d => pc.setLocalDescription(d))
.then(() => live && sc.send(JSON.stringify({ sdp: pc.localDescription })))
.catch(log);
};
pc.onsignalingstatechange = () => negotiating = pc.signalingState != "stable";
function scInit() {
sc.onmessage = e => wait(signalingDelayMs).then(() => {
var msg = JSON.parse(e.data);
if (msg.sdp) {
var desc = new RTCSessionDescription(JSON.parse(e.data).sdp);
if (desc.type == "offer") {
pc.setRemoteDescription(desc).then(() => pc.createAnswer())
.then(answer => pc.setLocalDescription(answer)).then(() => {
sc.send(JSON.stringify({ sdp: pc.localDescription }));
}).catch(log);
} else {
pc.setRemoteDescription(desc).catch(log);
}
} else if (msg.candidate) {
pc.addIceCandidate(new RTCIceCandidate(msg.candidate)).catch(log);
}
}).catch(log);
}
function dcInit() {
dc.onopen = () => {
live = true; update("Chat:"); chat.disabled = false; chat.select();
};
dc.onmessage = e => log(e.data);
}
function createOffer() {
button.disabled = true;
pc.onicecandidate = e => {
if (live) {
sc.send(JSON.stringify({ "candidate": e.candidate }));
} else if (!e.candidate) {
offer.value = pc.localDescription.sdp;
offer.select();
answer.placeholder = "Paste answer here";
}
};
dcInit(dc = pc.createDataChannel("chat"));
scInit(sc = pc.createDataChannel("signaling"));
};
offer.onkeypress = e => {
if (e.keyCode != 13 || pc.signalingState != "stable") return;
button.disabled = offer.disabled = true;
var obj = { type:"offer", sdp:offer.value };
pc.setRemoteDescription(new RTCSessionDescription(obj))
.then(() => pc.createAnswer()).then(d => pc.setLocalDescription(d))
.catch(log);
pc.onicecandidate = e => {
if (e.candidate) return;
if (!live) {
answer.focus();
answer.value = pc.localDescription.sdp;
answer.select();
} else {
sc.send(JSON.stringify({ "candidate": e.candidate }));
}
};
};
answer.onkeypress = e => {
if (e.keyCode != 13 || pc.signalingState != "have-local-offer") return;
answer.disabled = true;
var obj = { type:"answer", sdp:answer.value };
pc.setRemoteDescription(new RTCSessionDescription(obj)).catch(log);
};
chat.onkeypress = e => {
if (e.keyCode != 13) return;
dc.send(chat.value);
log("> " + chat.value);
chat.value = "";
};
function addTrack() {
pc.addStream(streams[0]);
flipButton.disabled = false;
removeAddButton.disabled = false;
}
var flipped = 0;
function flip() {
pc.getSenders()[0].replaceTrack(streams[flipped = 1 - flipped].getVideoTracks()[0])
.catch(log);
}
function removeAdd() {
if ("removeTrack" in pc) {
pc.removeTrack(pc.getSenders()[0]);
pc.addStream(streams[flipped = 1 - flipped]);
} else {
pc.removeStream(streams[flipped]);
pc.addStream(streams[flipped = 1 - flipped]);
}
}
var wait = ms => new Promise(resolve => setTimeout(resolve, ms));
var update = msg => div2.innerHTML = msg;
var log = msg => div.innerHTML += msg + "<br>";
<video id="v1" width="120" height="90" autoplay muted></video>
<video id="v2" width="120" height="90" autoplay></video><br>
<button id="button" onclick="createOffer()">Offer:</button>
<textarea id="offer" placeholder="Paste offer here"></textarea><br>
Answer: <textarea id="answer"></textarea><br>
<button id="button" onclick="addTrack()">AddTrack</button>
<button id="removeAddButton" onclick="removeAdd()" disabled>Remove+Add</button>
<button id="flipButton" onclick="flip()" disabled>ReplaceTrack (FF only)</button>
<div id="div"><p></div><br>
<table><tr><td><div id="div2">Not connected</div></td>
<td><input id="chat" disabled></input></td></tr></table><br>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
指示:
不涉及服务器,因此请点击Offer
,然后在两个选项卡之间手动剪切和回答(粘贴后按 ENTER 键)。
完成后,您可以通过数据通道聊天,然后点击addTrack
将视频添加到另一端。
Remove + Add
然后,您可以使用或切换远程显示的视频replaceTrack (FF only)
(如果您有要使用的辅助摄像头,请在 Chrome 中修改小提琴。)
重新协商现在都在数据通道上进行(不再是剪切粘贴)。