-
Notifications
You must be signed in to change notification settings - Fork 0
/
gum_picker_output.html
251 lines (228 loc) · 7.18 KB
/
gum_picker_output.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
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
<html>
<meta charset=utf-8>
<table>
<tr>
<td>
<button id="start">Start!</button><button id="halt">Stop!</button><br><br>
<table>
<tr>
<td>Camera:</td>
<td><select id="camera" disabled></select></td>
</tr>
<tr>
<td>Microphone:</td>
<td><select id="microphone" disabled></select></td>
</tr>
<tr>
<td>Speakers:</td>
<td>
<span>
<button id="speakers">Default system output...</button>
<button id="reset" hidden>Reset</button>
</span>
</td>
</tr>
</table><br><br><br>
</td>
<td>
<video id="video" width="266" height="200" autoplay controls></video><canvas id="canvas"></canvas><br>
</td>
</tr>
</table>
<div id="div"></div><br>
<script>
const console = {log: msg => div.innerHTML += `${msg}<br>`};
if (!localStorage.speakersLabel) {
localStorage.speakersLabel = "Default system output";
}
speakers.innerText = `${localStorage.speakersLabel}...`;
if (localStorage.speakers) {
reset.hidden = false;
}
async function getUserMedia(constraints) {
const stream = await navigator.mediaDevices.getUserMedia(constraints);
for (const track of stream.getTracks()) {
localStorage[track.kind] = track.getSettings().deviceId;
localStorage[track.kind + "Label"] = track.label;
track.addEventListener("ended", async () => {
try {
console.log(`${track.label}'s ${track.kind} track ended.`);
console.log(`Manually fall back to any available ${track.kind} device.`);
const [newTrack] = (await replaceUserMedia({audio: true})).getAudioTracks();
video.srcObject = spectrum(new MediaStream([newTrack, ...video.srcObject.getVideoTracks()]));
} catch (e) {
console.log(e);
}
}, {once:true});
}
return stream;
}
async function selectAudioOutput(options) {
const info = await navigator.mediaDevices.selectAudioOutput(options);
return info;
}
async function setSinkId({deviceId, label = "Default system output"}) {
if (deviceId == video.sinkId) return;
console.log(`Switching output to ${label}`);
await video.setSinkId(deviceId);
speakers.innerText = `${label}...`;
localStorage.speakers = deviceId;
localStorage.speakersLabel = label;
reset.hidden = !deviceId.length;
}
start.onclick = async () => {
try {
video.srcObject = spectrum(await getUserMedia({audio: {deviceId: localStorage.audio}, video: {deviceId: localStorage.video}}));
if (localStorage.speakers) {
await setSinkId(await selectAudioOutput({deviceId: localStorage.speakers}));
}
updateSelectors();
camera.disabled = microphone.disabled = false;
} catch (e) {
console.log(e);
}
};
halt.onclick = () => {
for (const track of video.srcObject.getTracks()) {
track.stop();
}
}
async function replaceUserMedia(constraints, ...oldTracks) {
try {
const stream = await getUserMedia(constraints);
for (const track of oldTracks) {
track.stop();
}
return stream;
} catch (e) {
if (e.name != "NotReadableError") throw e;
for (const track of oldTracks) {
track.stop();
}
return await getUserMedia(constraints);
}
}
microphone.onchange = async () => {
try {
const [oldTrack] = video.srcObject.getAudioTracks();
const [newTrack] = (await replaceUserMedia({audio: {deviceId: {exact: microphone.value}}}, oldTrack)).getAudioTracks();
video.srcObject = spectrum(new MediaStream([newTrack, ...video.srcObject.getVideoTracks()]));
} catch (e) {
console.log(e);
updateSelectors();
}
};
camera.onchange = async () => {
try {
const [oldTrack] = video.srcObject.getVideoTracks();
const [newTrack] = (await replaceUserMedia({video: {deviceId: {exact: camera.value}}}, oldTrack)).getVideoTracks();
video.srcObject = new MediaStream([newTrack, ...video.srcObject.getAudioTracks()]);
} catch (e) {
console.log(e);
updateSelectors();
}
};
speakers.onclick = async () => {
try {
await setSinkId(await selectAudioOutput());
} catch (e) {
console.log(e);
}
};
reset.onclick = async () => {
try {
await setSinkId({deviceId: ""});
} catch (e) {
console.log(e);
}
};
navigator.mediaDevices.ondevicechange = async () => {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
if (!devices.find(({deviceId}) => deviceId == video.sinkId)) {
reset.onclick();
}
const camCount = camera.childElementCount;
const micCount = microphone.childElementCount;
await updateSelectors();
if (camera.childElementCount > camCount) console.log("New camera available");
if (microphone.childElementCount > micCount) console.log("New microphone available");
} catch (e) {
console.log(e);
}
}
async function updateSelectors() {
try {
const selectedIds = (video.srcObject?.getTracks() || []).map(t => t.getSettings().deviceId);
if (video.sinkId) {
selectedIds.push(video.sinkId);
}
const devices = await navigator.mediaDevices.enumerateDevices();
for (const [s, type, kind, name] of [[camera, "video", "videoinput", "Camera"],
[microphone, "audio", "audioinput", "Microphone"]]) {
let old = s.value;
while (s.firstChild) s.removeChild(s.firstChild);
let i = 0;
for (const device of devices) {
if (device.kind != kind) continue;
const option = document.createElement('option');
option.value = device.deviceId;
i++;
const match = device.deviceId == localStorage[type];
option.text = device.label || (match && localStorage[type+"Label"]) || `${name} ${i}`;
if (match) old = option.value;
s.appendChild(option);
}
if ([...s.options].map(({value}) => value).includes(old)) s.value = old;
for (const option of s.options) {
if (selectedIds.includes(option.value)) s.value = option.value;
}
}
} catch (e) {
console.log(e);
}
}
updateSelectors();
function spectrum(stream) {
const audioCtx = new AudioContext();
const analyser = audioCtx.createAnalyser();
audioCtx.createMediaStreamSource(stream).connect(analyser);
canvas.width = 200;
canvas.height = 200;
const ctx = canvas.getContext("2d");
const data = new Uint8Array(canvas.width);
ctx.strokeStyle = 'rgb(0, 125, 0)';
const interval = setInterval(() => {
ctx.fillStyle = "#a0a0a0";
ctx.fillRect(0, 0, canvas.width, canvas.height);
analyser.getByteFrequencyData(data);
ctx.lineWidth = 2;
let x = 0;
for (let d of data) {
const y = canvas.height - (d / 128) * canvas.height / 4;
const c = Math.floor((x*255)/canvas.width);
ctx.fillStyle = `rgb(${c},0,${255-x})`;
ctx.fillRect(x++, y, 2, canvas.height - y)
}
analyser.getByteTimeDomainData(data);
ctx.lineWidth = 5;
ctx.beginPath();
x = 0;
for (let d of data) {
const y = canvas.height - (d / 128) * canvas.height / 2;
x ? ctx.lineTo(x++, y) : ctx.moveTo(x++, y);
}
ctx.stroke();
}, 1000 * canvas.width / audioCtx.sampleRate);
const cleanup = () => {
audioCtx.close();
clearInterval(interval);
};
const [track] = stream.getAudioTracks();
track.addEventListener("ended", cleanup, {once: true});
track.stop_ = track.stop;
track.stop = () => track.stop_(cleanup());
return stream;
};
</script>
</html>