Files
logic-puzzle/web/narration.js
T
2026-11-14 08:55:48 +01:00

66 lines
3.0 KiB
JavaScript

// One HTML media element per narrator, unlocked by a real user gesture.
// WebView hosts may still deny playback; the UI offers a retry in that case.
(() => {
const silence = 'data:audio/wav;base64,UklGRsQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
const players = new Map();
let nextId = 0;
const unlock = () => {
for (const player of players.values()) {
if (player.unlocked || player.unlocking) continue;
player.unlocking = true;
const audio = player.audio;
audio.src = silence;
audio.volume = 0;
let attempt;
try {
attempt = audio.play();
} catch (_) {
audio.volume = 1;
player.unlocking = false;
continue;
}
audio.volume = 1;
Promise.resolve(attempt).then(() => {
player.unlocked = true;
if (audio.src === silence) { audio.pause(); audio.currentTime = 0; }
}).catch(() => {}).finally(() => { player.unlocking = false; });
}
};
document.addEventListener('pointerdown', unlock, true);
// Older embedded WebViews may emit touch or mouse events without PointerEvent.
document.addEventListener('touchstart', unlock, { capture: true, passive: true });
document.addEventListener('mousedown', unlock, true);
document.addEventListener('keydown', unlock, true);
window.lumenNarration = {
create(onChange) {
const id = ++nextId;
const audio = new Audio(silence);
audio.preload = 'auto';
const player = { audio, onChange, unlocked: false, unlocking: false, disposed: false };
for (const event of ['playing', 'pause', 'ended', 'timeupdate', 'durationchange', 'error']) {
audio.addEventListener(event, () => {
if (player.disposed) return;
if (event === 'playing' && audio.src !== silence) player.unlocked = true;
onChange();
});
}
players.set(id, player);
return id;
},
play(id, url, speed, reload) {
const audio = players.get(id).audio;
if (reload || audio.src !== url) audio.src = url;
else if (audio.ended) audio.currentTime = 0;
audio.playbackRate = speed;
return audio.play();
},
pause(id) { players.get(id).audio.pause(); },
stop(id) { const a = players.get(id).audio; a.pause(); try { a.currentTime = 0; } catch (_) {} },
dispose(id) { const p = players.get(id); if (!p) return; p.disposed = true; p.audio.pause(); p.audio.removeAttribute('src'); p.audio.load(); players.delete(id); },
playing(id) { const a = players.get(id).audio; return !a.paused && !a.ended && a.src !== silence; },
finished(id) { return players.get(id).audio.ended; },
position(id) { return (players.get(id).audio.currentTime || 0) * 1000; },
duration(id) { const n = players.get(id).audio.duration; return Number.isFinite(n) ? n * 1000 : 0; },
};
})();