-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudiosink.html
More file actions
361 lines (320 loc) · 15.3 KB
/
audiosink.html
File metadata and controls
361 lines (320 loc) · 15.3 KB
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Route this page’s audio to “NDI Audio” (setSinkId only)</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
:root { font-family: system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif; }
body { max-width: 860px; margin: 2rem auto; padding: 0 1rem; }
h1 { font-size: 1.4rem; margin-bottom: .25rem; }
.row { display:flex; gap:.75rem; align-items:center; flex-wrap:wrap; margin:.5rem 0; }
button, select, input[type="range"] { font-size: 1rem; padding: .5rem .75rem; }
.note { color:#555; }
.err { color:#b00020; white-space: pre-wrap; }
details { margin-top: 1rem; }
audio { width: 100%; }
.meter { width: 160px; height: 12px; background: #eee; border-radius: 6px; overflow: hidden; }
.bar { height: 100%; width: 0%; background: #4a90e2; transition: width .05s linear; }
.warn { padding: .5rem .75rem; background: #fff7e6; border: 1px solid #ffd27a; border-radius: 6px; }
</style>
</head>
<body>
<h1>Route this page’s audio to a specific output (e.g., “NDI Audio”)</h1>
<p class="note">
Use Chromium (Chrome/Edge/Brave) on desktop over <b>HTTPS</b> or <code>http://localhost</code>.
Safari doesn’t support <code>setSinkId()</code>.
</p>
<!-- Device picker -->
<div class="row">
<button id="btnList">Show output devices</button>
<select id="sinks" disabled aria-label="Audio output devices"></select>
<button id="btnApply" disabled>Apply to this page</button>
<span id="status" class="note"></span>
</div>
<p id="banner" class="warn" style="display:none;"></p>
<p id="error" class="err"></p>
<hr>
<!-- Test tone -->
<h2>Test tone</h2>
<div class="row">
<button id="btnStart">Start 440 Hz</button>
<button id="btnStop" disabled>Stop</button>
<label>Volume <input id="gain" type="range" min="0" max="100" value="35"></label>
<span class="meter" title="Tone level"><span id="toneVu" class="bar"></span></span>
</div>
<!-- File player -->
<h2>Play your own file</h2>
<div class="row">
<input id="file" type="file" accept="audio/*">
</div>
<audio id="player" controls></audio>
<div class="row">
<span class="meter" title="Player level"><span id="fileVu" class="bar"></span></span>
</div>
<!-- Hidden audio sink for WebAudio tone -->
<audio id="out" autoplay></audio>
<details>
<summary>Troubleshooting</summary>
<ul>
<li>If labels are blank, the page will ask for a one-time mic permission to reveal device labels.</li>
<li>If your chosen sink disappears (USB/BT unplug), the page will fall back to <code>default</code> and log it.</li>
<li>Check the Console for timestamped logs (apply attempts, retries, devicechange events, etc.).</li>
</ul>
</details>
<script>
(function () {
// ---------- Logging helpers ----------
const ts = () => new Date().toISOString().replace('T',' ').replace('Z','');
const log = (...a) => console.log(`[${ts()}]`, ...a);
const info = (...a) => console.info(`[${ts()}]`, ...a);
const warn = (...a) => console.warn(`[${ts()}]`, ...a);
const err = (...a) => console.error(`[${ts()}]`, ...a);
// ---------- Elements ----------
const outEl = document.getElementById('out'); // WebAudio tone sink
const player = document.getElementById('player'); // File player sink
const btnList = document.getElementById('btnList');
const sinks = document.getElementById('sinks');
const btnApply= document.getElementById('btnApply');
const btnStart= document.getElementById('btnStart');
const btnStop = document.getElementById('btnStop');
const gainCtl = document.getElementById('gain');
const fileInp = document.getElementById('file');
const statusEl= document.getElementById('status');
const errorEl = document.getElementById('error');
const banner = document.getElementById('banner');
const toneVu = document.getElementById('toneVu');
const fileVu = document.getElementById('fileVu');
// ---------- State ----------
let ac = null, osc = null, gainNode = null, dest = null, playing = false;
let toneAnalyser = null, fileAnalyser = null, fileCtx = null, fileSrc = null;
let currentSinkId = 'default'; // what we *think* we’re routing to
let lastDeviceList = []; // cache of latest outputs
const setStatus = m => { statusEl.textContent = m || ''; if (m) info('STATUS:', m); };
const setError = m => { errorEl.textContent = m || ''; if (m) err('UI ERROR:', m); };
const showBanner= m => { banner.textContent = m; banner.style.display = m ? '' : 'none'; if (m) warn('BANNER:', m); };
const supportsSinkId = el => typeof el.setSinkId === 'function';
// ---------- Audio graphs ----------
function buildToneGraph() {
if (!ac) ac = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 48000 });
osc = ac.createOscillator(); osc.type = 'sine'; osc.frequency.setValueAtTime(440, ac.currentTime);
gainNode = ac.createGain(); gainNode.gain.setValueAtTime(gainCtl.value/100, ac.currentTime);
dest = ac.createMediaStreamDestination();
toneAnalyser = ac.createAnalyser(); toneAnalyser.fftSize = 256;
osc.connect(gainNode);
gainNode.connect(toneAnalyser);
gainNode.connect(dest);
outEl.srcObject = dest.stream;
osc.addEventListener('ended', () => {
playing = false;
try { osc.disconnect(); gainNode.disconnect(); } catch {}
btnStart.disabled = false; btnStop.disabled = true;
setStatus('Tone stopped.');
}, { once:true });
info('Tone graph built. sampleRate=', ac.sampleRate);
}
function startMeters() {
(function loopTone() {
if (toneAnalyser) {
const data = new Uint8Array(toneAnalyser.frequencyBinCount);
toneAnalyser.getByteTimeDomainData(data);
let peak = 0; for (let i=0;i<data.length;i++) { const v = Math.abs(data[i]-128); if (v>peak) peak=v; }
toneVu.style.width = Math.min(100, (peak/128)*100) + '%';
}
requestAnimationFrame(loopTone);
})();
(function loopFile() {
if (fileAnalyser) {
const data = new Uint8Array(fileAnalyser.frequencyBinCount);
fileAnalyser.getByteTimeDomainData(data);
let peak = 0; for (let i=0;i<data.length;i++) { const v = Math.abs(data[i]-128); if (v>peak) peak=v; }
fileVu.style.width = Math.min(100, (peak/128)*100) + '%';
}
requestAnimationFrame(loopFile);
})();
}
// ---------- Robust setSinkId with retry/backoff ----------
async function safeApplySinkToElement(el, deviceId, labelForLog, { retries = 3, delays = [50, 150, 400] } = {}) {
if (!supportsSinkId(el)) {
throw new Error('setSinkId() unsupported in this browser for element.');
}
// For HTMLMediaElement, pausing can help avoid AbortError during device switches
let wasPlaying = false;
try {
if (!el.paused && !el.ended) { wasPlaying = true; el.pause(); info(`${labelForLog}: paused before setSinkId`); }
} catch(e) { /* ignore if not applicable */ }
let lastErr;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
info(`${labelForLog}: setSinkId("${deviceId}") attempt ${attempt+1}/${retries+1}`);
await el.setSinkId(deviceId);
info(`${labelForLog}: setSinkId OK → ${deviceId}`);
// Resume if we paused
if (wasPlaying) {
try { await el.play(); info(`${labelForLog}: resumed after setSinkId`); } catch (e) { warn(`${labelForLog}: resume failed`, e); }
}
return; // success
} catch (e) {
lastErr = e;
const name = (e && e.name) || 'Error';
const msg = (e && e.message) || String(e);
warn(`${labelForLog}: setSinkId failed [${name}] ${msg}`);
// Known transient cases: AbortError, NotAllowedError right after device change
if (attempt < retries) {
const d = delays[Math.min(attempt, delays.length-1)];
info(`${labelForLog}: retrying in ${d}ms...`);
await new Promise(r => setTimeout(r, d));
continue;
}
}
}
// After exhausting retries, rethrow
throw lastErr || new Error('setSinkId failed after retries');
}
async function applySinkToPage(deviceId, deviceLabel) {
setError('');
try {
info('Applying sink to page:', { deviceId, deviceLabel });
await safeApplySinkToElement(outEl, deviceId, 'Tone sink');
await safeApplySinkToElement(player, deviceId, 'File player');
currentSinkId = deviceId;
setStatus(`Output routed to: ${deviceLabel || deviceId}`);
showBanner('');
} catch (e) {
const name = (e && e.name) || 'Error';
const msg = (e && e.message) || String(e);
setError(`setSinkId failed: ${msg}`);
err('applySinkToPage: final failure', name, msg, e);
}
}
// ---------- Device list handling ----------
async function enumerateOutputs(showPromptForLabels = true) {
setError('');
let devices = await navigator.mediaDevices.enumerateDevices();
const haveLabels = devices.some(d => d.kind === 'audiooutput' && d.label);
if (!haveLabels && showPromptForLabels) {
try {
info('Requesting one-time mic permission to reveal device labels…');
const s = await navigator.mediaDevices.getUserMedia({ audio: true });
s.getTracks().forEach(t => t.stop());
devices = await navigator.mediaDevices.enumerateDevices();
} catch (e) {
warn('Mic permission denied (labels may be blank).');
}
}
const outs = devices.filter(d => d.kind === 'audiooutput');
lastDeviceList = outs;
info('Outputs:', outs.map(o => ({ id:o.deviceId, label:o.label })));
return outs;
}
function refreshSelect(outs, preserveSelection = true) {
const prev = preserveSelection ? sinks.value : null;
sinks.innerHTML = '';
outs.forEach(d => {
const opt = document.createElement('option');
opt.value = d.deviceId;
opt.textContent = d.label || ('Output ' + d.deviceId);
sinks.appendChild(opt);
});
let selectedId = prev && outs.some(d => d.deviceId === prev) ? prev : (outs[0]?.deviceId || '');
if (selectedId) sinks.value = selectedId;
const haveAny = outs.length > 0;
sinks.disabled = !haveAny;
btnApply.disabled = !haveAny;
return selectedId;
}
// ---------- UI Handlers ----------
btnStart.addEventListener('click', async () => {
try {
setError('');
if (playing) return;
buildToneGraph();
await ac.resume();
osc.start(); playing = true;
btnStart.disabled = true; btnStop.disabled = false;
setStatus('Tone playing. Choose “NDI Audio” and click Apply.');
} catch (e) { setError('Failed to start tone: ' + (e.message || e)); err(e); }
});
btnStop.addEventListener('click', () => {
try { if (playing && osc) osc.stop(); } catch (e) { setError('Failed to stop tone: ' + (e.message || e)); err(e); }
});
gainCtl.addEventListener('input', () => {
if (gainNode && ac) gainNode.gain.setValueAtTime(gainCtl.value/100, ac.currentTime);
});
fileInp.addEventListener('change', () => {
const f = fileInp.files && fileInp.files[0];
if (!f) return;
player.src = URL.createObjectURL(f);
player.play().catch(()=>{});
if (!fileCtx) fileCtx = new (window.AudioContext || window.webkitAudioContext)();
try {
if (fileSrc) fileSrc.disconnect();
fileSrc = fileCtx.createMediaElementSource(player);
fileAnalyser = fileCtx.createAnalyser(); fileAnalyser.fftSize = 256;
fileSrc.connect(fileAnalyser).connect(fileCtx.destination);
} catch (_) {
// MediaElementSource may only be created once per element; ignore if already attached
}
});
btnList.addEventListener('click', async () => {
try {
const outs = await enumerateOutputs(true);
if (!outs.length) { setError('No audio outputs found. Use Chrome/Edge on desktop.'); return; }
const selected = refreshSelect(outs, true);
setStatus('Pick an output (look for “NDI Audio”).');
info('Device list shown. Preselected:', selected);
} catch (e) { setError('enumerateDevices failed: ' + (e.message || e)); err(e); }
});
btnApply.addEventListener('click', async () => {
const id = sinks.value;
if (!id) { setError('Pick a device first.'); return; }
const selectedLabel = sinks.selectedOptions[0]?.textContent || '';
await applySinkToPage(id, selectedLabel);
});
// ---------- React to device changes ----------
if (navigator.mediaDevices && 'ondevicechange' in navigator.mediaDevices) {
navigator.mediaDevices.addEventListener('devicechange', async () => {
warn('devicechange event fired — outputs likely changed.');
try {
const outs = await enumerateOutputs(false);
const stillThere = outs.some(d => d.deviceId === currentSinkId);
const selectedAfterRefresh = refreshSelect(outs, true);
if (stillThere) {
info('Current sink still available:', currentSinkId, 'Re-applying sink to ensure continuity.');
try {
const label = outs.find(d => d.deviceId === currentSinkId)?.label || currentSinkId;
await applySinkToPage(currentSinkId, label);
} catch (e) {
warn('Re-apply after devicechange failed; will stay on current routing:', e);
}
showBanner('');
} else {
// Fallback to default sink
const label = outs.find(d => d.deviceId === 'default')?.label || 'default';
showBanner('Previously selected output disappeared. Falling back to default output.');
info('Falling back to default sink after devicechange.');
await applySinkToPage('default', label);
// Keep the UI select coherent
if (selectedAfterRefresh !== 'default' && outs.some(o => o.deviceId === 'default')) {
sinks.value = 'default';
}
}
} catch (e) {
err('devicechange handling failed:', e);
}
});
} else {
warn('devicechange not supported; dynamic device swaps may require manual re-apply.');
}
// ---------- Init ----------
startMeters();
if (supportsSinkId(outEl) && supportsSinkId(player)) {
setStatus('Ready. Start the tone or load a file, then pick “NDI Audio” and Apply.');
} else {
setStatus('This browser lacks setSinkId(); use Chrome/Edge desktop.');
}
info('Page initialized. setSinkId support (tone,player)=', supportsSinkId(outEl), supportsSinkId(player));
})();
</script>
</body>
</html>