Article WebRTC Stage 3
by jib1
HTML
<label><input type="checkbox" id="checkbox">Add video to audio-call (turn this on and off) </label>
<button onclick="stream.getTracks().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, videoTransceiver;
(async () => {
try {
stream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
videoTrack = stream.getVideoTracks()[0];
pc1.addTransceiver(stream.getAudioTracks()[0], {direction: "sendonly", streams: [stream]});
videoTransceiver = pc1.addTransceiver("video", {direction: "inactive", streams: [stream]});
} catch (e) {
console.log(e);
}
})();
checkbox.onclick = async () => {
if (checkbox.checked) {
await videoTransceiver.sender.replaceTrack(videoTrack);
videoTransceiver.direction = "sendonly";
} else {
await videoTransceiver.sender.replaceTrack(null);
videoTransceiver.direction = "inactive";
}
}
pc2.ontrack = e => {
video.srcObject = e.streams[0];
}
pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.onnegotiationneeded = async e => {
try {
await pc1.setLocalDescription(await pc1.createOffer());
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription(await pc2.createAnswer());
await pc1.setRemoteDescription(pc2.localDescription);
} catch (e) {
console.log(e);
}
}