-
Notifications
You must be signed in to change notification settings - Fork 256
/
Copy pathindex.html
100 lines (82 loc) · 2.52 KB
/
index.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<!DOCTYPE html>
<html>
<!--
SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
SPDX-License-Identifier: MIT
-->
<head>
<meta charset="utf-8">
</head>
<body>
<h3> Local Video </h3>
<video id="localVideo" width="160" height="120" autoplay muted></video> <br />
<h3> Remote Video </h3>
<div id="remoteVideos"></div> <br />
<h3> Logs </h3>
<div id="logs"></div>
</body>
<script>
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => {
let pc = new RTCPeerConnection()
pc.ontrack = function (event) {
if (event.track.kind === 'audio') {
return
}
let el = document.createElement(event.track.kind)
el.srcObject = event.streams[0]
el.autoplay = true
el.controls = true
document.getElementById('remoteVideos').appendChild(el)
event.track.onmute = function(event) {
el.play()
}
event.streams[0].onremovetrack = ({track}) => {
if (el.parentNode) {
el.parentNode.removeChild(el)
}
}
}
document.getElementById('localVideo').srcObject = stream
stream.getTracks().forEach(track => pc.addTrack(track, stream))
let ws = new WebSocket("{{.}}")
pc.onicecandidate = e => {
if (!e.candidate) {
return
}
ws.send(JSON.stringify({event: 'candidate', data: JSON.stringify(e.candidate)}))
}
ws.onclose = function(evt) {
window.alert("Websocket has closed")
}
ws.onmessage = function(evt) {
let msg = JSON.parse(evt.data)
if (!msg) {
return console.log('failed to parse msg')
}
switch (msg.event) {
case 'offer':
let offer = JSON.parse(msg.data)
if (!offer) {
return console.log('failed to parse answer')
}
pc.setRemoteDescription(offer)
pc.createAnswer().then(answer => {
pc.setLocalDescription(answer)
ws.send(JSON.stringify({event: 'answer', data: JSON.stringify(answer)}))
})
return
case 'candidate':
let candidate = JSON.parse(msg.data)
if (!candidate) {
return console.log('failed to parse candidate')
}
pc.addIceCandidate(candidate)
}
}
ws.onerror = function(evt) {
console.log("ERROR: " + evt.data)
}
}).catch(window.alert)
</script>
</html>