-
Notifications
You must be signed in to change notification settings - Fork 641
/
Copy pathwebrtc-sync.html
66 lines (57 loc) · 2 KB
/
webrtc-sync.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>go2rtc - WebRTC</title>
<style>
body {
background-color: black;
margin: 0;
padding: 0;
}
html, body, video {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<video id="video" autoplay controls playsinline muted></video>
<script>
async function PeerConnection(media) {
const pc = new RTCPeerConnection({
iceServers: [{urls: 'stun:stun.l.google.com:19302'}]
});
document.getElementById('video').srcObject = new MediaStream([
pc.addTransceiver('audio', {direction: 'sendrecv'}).receiver.track,
pc.addTransceiver('video', {direction: 'sendrecv'}).receiver.track,
]);
const tracks = await navigator.mediaDevices.getUserMedia({
video: media.indexOf('camera') >= 0,
audio: media.indexOf('microphone') >= 0,
});
tracks.getTracks().forEach(track => {
pc.addTrack(track);
});
return pc;
}
function getCompleteOffer(pc, timeout) {
return new Promise((resolve, reject) => {
pc.addEventListener('icegatheringstatechange', () => {
if (pc.iceGatheringState === 'complete') resolve(pc.localDescription.sdp);
});
pc.createOffer().then(offer => pc.setLocalDescription(offer));
setTimeout(() => resolve(pc.localDescription.sdp), timeout || 3000);
});
}
async function connect() {
const media = new URLSearchParams(location.search).get('media');
const pc = await PeerConnection(media);
const url = new URL('api/webrtc' + location.search, location.href);
const r = await fetch(url, {method: 'POST', body: await getCompleteOffer(pc)});
await pc.setRemoteDescription({type: 'answer', sdp: await r.text()});
}
connect();
</script>
</body>
</html>