JSFiddle - React, Tailwind, and code Playground
by Nikolay Vasilchuk
HTML
<video id="video1" width="320" height="240" autoplay controls muted></video><br>
<video id="video2" width="320" height="240" autoplay controls></video><br>
<select id="videoSource">
<option value="">- Fake -</option>
</select>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
JavaScript
navigator.mediaDevices.enumerateDevices().then(function(devices) {
devices.forEach(function(device) {
if (device.kind === 'videoinput') {
var option = document.createElement('option');
option.value = device.deviceId;
option.text = device.label;
videoSource.appendChild(option);
}
});
});
function getFakeMediaStream() {
function getSilence() {
var ctx = new AudioContext(),
oscillator = ctx.createOscillator(),
dst = oscillator.connect(ctx.createMediaStreamDestination());
oscillator.start();
return Object.assign(dst.stream.getAudioTracks()[0], {enabled: false});
}
function getBlack() {
context.fillRect(0, 0, 640, 480);
return canvas.captureStream().getVideoTracks()[0];
}
return new MediaStream([getBlack(), getSilence()]);
}
var canvas = Object.assign(document.createElement('canvas'), {width: 640, height: 480});
var context = canvas.getContext('2d');
var camAttached = false;
var fakeStream = getFakeMediaStream();
var stream = fakeStream.clone();
var pc1 = new RTCPeerConnection();
var pc2 = new RTCPeerConnection();
pc1.onicecandidate = function(e) {
pc2.addIceCandidate(e.candidate);
};
pc2.onicecandidate = function(e) {
pc1.addIceCandidate(e.candidate);
};
pc2.onaddstream = function(e) {
video2.srcObject = e.stream;
}
video1.srcObject = stream;
stream.getTracks().forEach(function(track) {
pc1.addTrack(track, stream);
});
pc1.createOffer().then(offer => pc1.setLocalDescription(offer))
.then(() => pc2.setRemoteDescription(pc1.localDescription))
.then(() => pc2.createAnswer()).then(answer => pc2.setLocalDescription(answer))
.then(() => pc1.setRemoteDescription(pc2.localDescription));
function draw() {
if (camAttached) {
context.drawImage(video1, 0, 0, 640, 480);
requestAnimationFrame(draw);
} else {
context.fillStyle="#0000FF";
context.fillRect(0, 0, 640, 480);
}
}
function switchCam(deviceId) {
navigator.mediaDevices.getUserMedia({video: {width: 640,...