-
Notifications
You must be signed in to change notification settings - Fork 0
/
webrtc.html
104 lines (85 loc) · 3.08 KB
/
webrtc.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
101
102
103
104
<html>
<head>
<script type="text/javascript" src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script type="text/javascript">
var html5VideoElement;
var html5AudioElement;
var websocketConnection;
var webrtcPeerConnection;
var webrtcConfiguration;
var reportError;
function onLocalDescription(desc)
{
console.log("Local description: " + JSON.stringify(desc));
webrtcPeerConnection.setLocalDescription(desc).then(function() {
websocketConnection.send(JSON.stringify({ type: "sdp", "data": webrtcPeerConnection.localDescription }));
}).catch(reportError);
}
function onIncomingSDP(sdp)
{
console.log("Incoming SDP: " + JSON.stringify(sdp));
webrtcPeerConnection.setRemoteDescription(sdp).catch(reportError);
webrtcPeerConnection.createAnswer().then(onLocalDescription).catch(reportError);
}
function onIncomingICE(ice)
{
var candidate = new RTCIceCandidate(ice);
console.log("Incoming ICE: " + JSON.stringify(ice));
webrtcPeerConnection.addIceCandidate(candidate).catch(reportError);
}
function onAddRemoteStream(event)
{
html5VideoElement.srcObject = event.streams[0];
html5AudioElement.srcObject = event.streams[0];
}
function onIceCandidate(event)
{
if (event.candidate == null)
return;
console.log("Sending ICE candidate out: " + JSON.stringify(event.candidate));
websocketConnection.send(JSON.stringify({ "type": "ice", "data": event.candidate }));
}
function onServerMessage(event)
{
var msg;
try {
msg = JSON.parse(event.data);
} catch (e) {
return;
}
if (!webrtcPeerConnection) {
webrtcPeerConnection = new RTCPeerConnection(webrtcConfiguration);
webrtcPeerConnection.ontrack = onAddRemoteStream;
webrtcPeerConnection.onicecandidate = onIceCandidate;
}
switch (msg.type) {
case "sdp": onIncomingSDP(msg.data); break;
case "ice": onIncomingICE(msg.data); break;
default: break;
}
}
function playStream(configuration)
{
const l = window.location;
const wsUrl = "ws://" + l.hostname + ":" + l.port + "/ws";
html5VideoElement = document.getElementById("stream");
html5AudioElement = document.getElementById("astream");
webrtcConfiguration = configuration;
reportError = (errmsg) => { console.error(errmsg); };
websocketConnection = new WebSocket(wsUrl);
websocketConnection.addEventListener("message", onServerMessage);
}
window.onload = function() {
playStream({
'iceServers': [{ 'urls': 'stun:%STUN_SERVER%' }]
});
};
</script>
</head>
<body>
<div>
<video id="stream" autoplay playsinline>Your browser does not support video</video>
<audio controls id="astream" >Your browser does not support video</audio>
</div>
</body>
</html>