Article WebRTC Stage 1
by jib1
HTML
<label><input type="checkbox" id="checkbox">Add video to audio-call (turn this on and off) </label>
<button onclick="[...stream.getTracks(), videoTrack].forEach(t => t.stop())">Stop Example</button><br>
<video id="video" width="320" height="240" autoplay controls></video>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
JavaScript
let pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection(), stream, videoTrack;
(async () => {
try {
stream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
stream.removeTrack(videoTrack = stream.getVideoTracks()[0]);
pc1.addStream(stream);
} catch (e) {
console.log(e);
}
})();
checkbox.onclick = () => {
pc1.removeStream(stream);
if (checkbox.checked) {
stream.addTrack(videoTrack);
} else {
stream.removeTrack(videoTrack);
}
pc1.addStream(stream);
}
pc2.onaddstream = e => {
e.stream.onaddtrack = e => {
e.track.onended = e => video.srcObject = video.srcObject; // Chrome/Firefox bug
}
video.srcObject = e.stream;
}
// Firefox never implemented removeStream because the spec changed, so we polyfill it here:
if (!("removeStream" in RTCPeerConnection.prototype)) {
RTCPeerConnection.prototype.removeStream = function(stream) {
this.getSenders().forEach(s => stream.getTracks().includes(s.track) && this.removeTrack(s));
}
}
pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
let negotiating = false;
pc1.onnegotiationneeded = async e => {
try {
if (negotiating) return; // Work around a Chrome bug
negotiating = true;
await pc1.setLocalDescription(await pc1.createOffer());
negotiating = false;
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription(await pc2.createAnswer());
await pc1.setRemoteDescription(pc2.localDescription);
} catch (e) {
console.log(e);
}
}