visit
What is WebRTC?
WebRTC stands for Web Real Time Communication. From webrtc.org:"With WebRTC, you can add real-time communication capabilities to your application that works on top of an open standard. It supports video, voice, and generic data to be sent between peers, allowing developers to build powerful voice and video communication solutions"The API is actually not so big and complicated as it sounds. The MDN website is, as always, very complete . We have 3 main parts:
<video id="localVideo" playsinline autoplay muted></video>
<video id="remoteVideo" playsinline autoplay></video>
<button id="startButton">Start</button>
<button id="callButton">Call</button>
<button id="hangupButton">Hang Up</button>
const startButton = document.getElementById("startButton");
const callButton = document.getElementById("callButton");
const hangupButton = document.getElementById("hangupButton");
startButton.addEventListener("click", start);
callButton.addEventListener("click", call);
hangupButton.addEventListener("click", hangup);
const localVideo = document.getElementById("localVideo");
const remoteVideo = document.getElementById("remoteVideo");
let localStream;
let pc1;
let pc2;
const offerOptions = {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1,
};
async function start() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: true,
video: true,
});
localVideo.srcObject = stream;
localStream = stream;
} catch (e) {
alert(`getUserMedia() error: ${e.name}`);
}
}
async function call() {
const configuration = {};
pc1 = new RTCPeerConnection(configuration);
pc1.addEventListener("icecandidate", (e) => onIceCandidate(pc1, e));
pc2 = new RTCPeerConnection(configuration);
pc2.addEventListener("icecandidate", (e) => onIceCandidate(pc2, e));
pc2.addEventListener("track", gotRemoteStream);
localStream.getTracks().forEach((track) => pc1.addTrack(track, localStream));
try {
await pc1.createOffer(offerOptions);
await onCreateOfferSuccess()
} catch (e) {
onCreateSessionDescriptionError(e);
}
}
async function onCreateOfferSuccess() {
try {
await pc2.createAnswer();
} catch (e) {
onCreateSessionDescriptionError(e);
}
}
function onCreateSessionDescriptionError(error) {
console.log(`Failed to create session description: ${error.toString()}`);
}
function getName(pc) {
return pc === pc1 ? "pc1" : "pc2";
}
function getOtherPc(pc) {
return pc === pc1 ? pc2 : pc1;
}
async function onIceCandidate(pc, event) {
try {
await getOtherPc(pc).addIceCandidate(event.candidate);
} catch (e) {
onAddIceCandidateError(pc, e);
}
}
function onAddIceCandidateError(pc, error) {
console.log(
`${getName(pc)} failed to add ICE Candidate: ${error.toString()}`
);
}
function gotRemoteStream(e) {
if (remoteVideo.srcObject !== e.streams[0]) {
remoteVideo.srcObject = e.streams[0];
}
}
function hangup() {
pc1.close();
pc2.close();
pc1 = null;
pc2 = null;
}