Skip to content

Instantly share code, notes, and snippets.

@sboily
Last active August 11, 2021 22:56
Show Gist options
  • Save sboily/624bb168eb6da4cfa4547e90039f55fe to your computer and use it in GitHub Desktop.
Save sboily/624bb168eb6da4cfa4547e90039f55fe to your computer and use it in GitHub Desktop.
let pc, stream;
const constraints = window.constraints = {
audio: true,
video: true
};
function viewStream() {
const video = document.querySelector('video#localVideo');
video.srcObject = stream;
video.play();
document.querySelector('#makeCall').disabled = false;
}
async function init(e) {
try {
stream = await navigator.mediaDevices.getUserMedia(constraints);
viewStream();
} catch (e) {
console.log(e);
}
}
function makeCall() {
const configuration = {'iceServers': [{'urls': 'stun:stun.wazo.io:443'}]}
pc = new RTCPeerConnection(configuration);
if (stream) {
stream.getTracks().forEach(track => {
pc.addTrack(track);
});
}
pc.onicecandidate = iceCallback;
createSDP(false);
}
async function createSDP(ice) {
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
if (ice) {
console.log(offer.sdp);
}
}
async function removeVideo() {
const video = document.querySelector('video#localVideo');
stream.getVideoTracks().forEach(track => {
track.enabled = !track.enabled;
track.stop()
stream.removeTrack(track);
});
video.srcObject = stream;
}
function hangupCall() {
stream.getTracks().forEach(track => {
track.enabled = !track.enabled;
track.stop()
});
const video = document.querySelector('video#localVideo');
video.srcObject = stream;
pc.close();
stream = null;
document.querySelector('#makeCall').disabled = true;
}
function iceCallback(event) {
if (event?.target?.iceGatheringState === 'complete') {
createSDP(true);
}
}
document.querySelector('#makeCall').disabled = true;
document.querySelector('#showVideo').addEventListener('click', e => init(e));
document.querySelector('#makeCall').addEventListener('click', e => makeCall(e));
document.querySelector('#removeVideo').addEventListener('click', e => removeVideo(e));
document.querySelector('#hangupCall').addEventListener('click', e => hangupCall(e));
@sboily
Copy link
Author

sboily commented Aug 11, 2021

<div>
  <video id="localVideo"></video>
  <button id="showVideo">Open camera</button>
  <button id="removeVideo">Remove video</button>
  <button id="makeCall">Make call</button>
  <button id="hangupCall">Hangup call</button>
</div>

<script src="index.js"></script>

</body>
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment