Skip to content

Instantly share code, notes, and snippets.

@abdus
Created March 19, 2021 03:24
Show Gist options
  • Save abdus/9ed7520e93516d56119e95515999de21 to your computer and use it in GitHub Desktop.
Save abdus/9ed7520e93516d56119e95515999de21 to your computer and use it in GitHub Desktop.
WebRTC Example (Web, Plain JavaScript)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>WebRTC Practice</title>
</head>
<body>
<video
id="vid1"
src=""
style="height: 500px; width: 500px; border: 1px solid red"
></video>
<video
id="vid2"
src=""
style="height: 500px; width: 500px; border: 1px solid green"
></video>
<script src="./index.js"></script>
</body>
</html>
const vidOne = document.querySelector("#vid1");
const vidTwo = document.querySelector("#vid2");
const iceCfg = { iceServers: [{ urls: "stun:stun.l.google.com:19302" }] };
const peerConnOne = new RTCPeerConnection(iceCfg);
const peerConnTwo = new RTCPeerConnection(iceCfg);
async function getUserStream() {
const stream = navigator.mediaDevices.getUserMedia({
audio: false,
video: {
width: { min: 0 },
height: { min: 0 },
},
});
return stream;
}
async function makeCall() {
try {
const stream = await getUserStream();
stream.getTracks().forEach((tr) => peerConnOne.addTrack(tr, stream));
vidOne.srcObject = stream;
vidOne.onloadedmetadata = () => vidOne.play();
const offer = await peerConnOne.createOffer();
await peerConnOne.setLocalDescription(offer);
await peerConnTwo.setRemoteDescription(offer);
const answer = await peerConnTwo.createAnswer();
await peerConnTwo.setLocalDescription(answer);
await peerConnOne.setRemoteDescription(answer);
} catch (err) {
console.log(err);
}
}
makeCall();
// handle ICE
peerConnOne.onicecandidate = ({ candidate }) => {
candidate && peerConnTwo.addIceCandidate(candidate);
};
peerConnTwo.onicecandidate = ({ candidate }) => {
candidate && peerConnOne.addIceCandidate(candidate);
};
// check connection state
peerConnOne.onconnectionstatechange = (e) => {
console.log(`peerOne -----> `, e.currentTarget.connectionState);
};
peerConnTwo.onconnectionstatechange = (e) => {
console.log(`peerTwo -----> `, e.currentTarget.connectionState);
};
// handle remoteStream
let remoteStream = new MediaStream();
peerConnTwo.ontrack = (ev) => {
remoteStream.addTrack(ev.track, remoteStream);
};
vidTwo.srcObject = remoteStream;
vidTwo.onloadedmetadata = () => vidTwo.play();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment