-
Notifications
You must be signed in to change notification settings - Fork 0
/
webRTC.js
78 lines (61 loc) · 2.19 KB
/
webRTC.js
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
const socket = io("http://localhost:3000");
const boxStream = document.getElementById('box-stream');
const boxUsers = document.getElementById('box-users');
socket.emit('new-user', name);
socket.on('joined-user', users => {
boxUsers.innerHTML = "";
for (key in users) {
renderUsersEL(users[key]);
}
});
socket.on('user-active', users => {
boxUsers.innerHTML = "";
for (key in users) {
renderUsersEL(users[key]);
}
});
function renderUsersEL(user) {
let nel = document.createElement('li');
if (user == name) user += " - active";
nel.innerHTML = user;
boxUsers.appendChild(nel);
}
document.getElementById('stream-btn').addEventListener('click', broadcast);
let isClient = false;
const localSDP = document.getElementById('localSDP');
const clientSDP = document.getElementById('clientSDP');
const peerConnection = new RTCPeerConnection();
function broadcast() {
isClient = false;
const videoELement = document.createElement('video');
videoELement.muted = true;
let media = navigator.mediaDevices.getUserMedia({ 'video': true, 'audio': true });
media.then(stream => {
videoELement.srcObject = stream;
peerConnection.addStream(stream);
videoELement.play();
boxStream.appendChild(videoELement);
peerConnection.createOffer()
.then(sdp => peerConnection.setLocalDescription(sdp))
.then(() => {
localSDP.value = JSON.stringify(peerConnection.localDescription);
});
});
}
clientSDP.addEventListener('change', async e => {
if (isClient == true) return;
peerConnection.setRemoteDescription(JSON.parse(clientSDP.value))
.then(() => peerConnection.createAnswer())
.then(sdp => peerConnection.setLocalDescription(sdp))
.then(() => {
if (localSDP.value != "") return;
localSDP.value = JSON.stringify(peerConnection.localDescription);
});
peerConnection.onaddstream = event => {
const videoELement = document.createElement('video');
videoELement.muted = true;
videoELement.srcObject = event.stream;
videoELement.play();
boxStream.append(videoELement);
};
});