-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathptt.js
136 lines (112 loc) · 3.95 KB
/
ptt.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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/**
* Push-to-Talk object.
*/
const ptt = (function () {
var websocket;
var audiostream;
var button;
var id;
var initial = true;
var lastTimeStamp = new Date().getTime();
return {
connect: function () {
/**
* Binds UI button to ptt.
* @param {HTMLElement} btn
*/
const bind = (btn) => {
button = btn;
audiostream.getRecorder().then(recorder => {
button.onpointerdown = () => {
recorder.start();
button.disabled = true;
};
button.onpointerup = () => {
recorder.stop();
button.disabled = false;
};
button.onpointerout = () => {
if (button.disabled) {
recorder.stop();
button.disabled = false;
}
};
});
};
// add listener to foo
gunDB.get('audio').get(room).on(function (data, room) {
// console.log("received\n" + data.timestamp);
if (initial) {
initial = false;
return;
}
if (lastTimeStamp == data.timestamp) {
return;
}
lastTimeStamp = data.timestamp;
if (data.user == gunDB._.opt.pid) {
return;
}
if (data.event == 'started') {
if (button) {
button.disabled = true;
}
}
else if (data.event == 'stopped') {
if (button) {
button.disabled = false;
}
player.stop();
}
else if (data.event == 'metadata') {
var metadata = JSON.parse(data.data);
player = audiostream.getNewPlayer(metadata);
}
else if (data.event == 'binary') {
let byteCharacters = atob(data.data);
let byteArray = str2ab(byteCharacters);
player.play(byteArray);
}
})
return new Promise((resolve, reject) => {
var player;
var websocket = new Events()
audiostream = new AudioStream(websocket, {});
resolve({ bind });
websocket.addEventListener('started', event => {
if (button) {
button.disabled = true;
}
});
websocket.addEventListener('stopped', event => {
if (button) {
button.disabled = false;
}
player.stop();
});
websocket.addEventListener('metadata', metadata => {
player = audiostream.getNewPlayer(metadata);
});
websocket.addEventListener('binary', buffer => {
// var base64String = btoa(
// new Uint8Array(buffer)
// .reduce((onData, byte) => onData + String.fromCharCode(byte), ''));
let byteCharacters = atob(buffer);
let byteArray = str2ab(byteCharacters);
player.play(byteArray);
});
}).catch(function (err) {
reject(err);
});
}
}
})();
function str2ab(str) {
var buf = new ArrayBuffer(str.length);
var bufView = new Uint8Array(buf);
for (var i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
bufView = null;
return buf;
}