-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathscript.js
55 lines (49 loc) · 2.5 KB
/
script.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
//Create an account on Firebase, and use the credentials they give you in place of the following
var config = {
apiKey: "AIzaSyBajPcoloVgJTcE44NhPLvVsqnWG9RSBEE",
authDomain: "simple-webrtc-video-chat.firebaseapp.com",
databaseURL: "https://simple-webrtc-video-chat.firebaseio.com",
projectId: "simple-webrtc-video-chat",
storageBucket: "simple-webrtc-video-chat.appspot.com",
messagingSenderId: "748074977719"
};
firebase.initializeApp(config);
var database = firebase.database().ref();
var yourVideo = document.getElementById("yourVideo");
var friendsVideo = document.getElementById("friendsVideo");
var yourId = Math.floor(Math.random()*1000000000);
//Create an account on Viagenie (http://numb.viagenie.ca/), and replace {'urls': 'turn:numb.viagenie.ca','credential': 'websitebeaver','username': '[email protected]'} with the information from your account
var servers = {'iceServers': [{'urls': 'stun:stun.services.mozilla.com'}, {'urls': 'stun:stun.l.google.com:19302'}, {'urls': 'turn:numb.viagenie.ca','credential': 'beaver','username': '[email protected]'}]};
var pc = new RTCPeerConnection(servers);
pc.onicecandidate = (event => event.candidate?sendMessage(yourId, JSON.stringify({'ice': event.candidate})):console.log("Sent All Ice") );
pc.onaddstream = (event => friendsVideo.srcObject = event.stream);
function sendMessage(senderId, data) {
var msg = database.push({ sender: senderId, message: data });
msg.remove();
}
function readMessage(data) {
var msg = JSON.parse(data.val().message);
var sender = data.val().sender;
if (sender != yourId) {
if (msg.ice != undefined)
pc.addIceCandidate(new RTCIceCandidate(msg.ice));
else if (msg.sdp.type == "offer")
pc.setRemoteDescription(new RTCSessionDescription(msg.sdp))
.then(() => pc.createAnswer())
.then(answer => pc.setLocalDescription(answer))
.then(() => sendMessage(yourId, JSON.stringify({'sdp': pc.localDescription})));
else if (msg.sdp.type == "answer")
pc.setRemoteDescription(new RTCSessionDescription(msg.sdp));
}
};
database.on('child_added', readMessage);
function showMyFace() {
navigator.mediaDevices.getUserMedia({audio:true, video:true})
.then(stream => yourVideo.srcObject = stream)
.then(stream => pc.addStream(stream));
}
function showFriendsFace() {
pc.createOffer()
.then(offer => pc.setLocalDescription(offer) )
.then(() => sendMessage(yourId, JSON.stringify({'sdp': pc.localDescription})) );
}