/**
* Client-side playback of an already generated local audio asset.
* This module never accesses ElevenLabs and needs no API key.
* It does not control scrolling. A separate tour controller can call start().
*
* Required HTML:
*
*
*
*
* const sound = createNarrationController({
* audio: document.querySelector('#narration'),
* button: document.querySelector('#sound-toggle'),
* status: document.querySelector('#sound-status'),
* attemptOnFirstScroll: false,
* });
*
* // Invoke from an explicit button handler, before unrelated await operations:
* tourButton.addEventListener('click', () => {
* void sound.start();
* tour.start();
* });
*/
export function createNarrationController({
audio,
button,
status,
attemptOnFirstScroll = false,
storageKey = 'cinematic-site-sound-choice',
}) {
if (!audio || !button) throw new Error('Audio element and sound button are required.');
const listeners = new AbortController();
const options = { signal: listeners.signal };
let requestVersion = 0;
let pending = false;
let destroyed = false;
let firstScrollAttempted = false;
let manuallyPaused = false;
const initialScrollY = window.scrollY;
try {
manuallyPaused = localStorage.getItem(storageKey) === 'paused';
} catch {
// Storage can be unavailable; playback still works for this visit.
}
function remember(value) {
try { localStorage.setItem(storageKey, value); } catch { /* Optional preference */ }
}
function render(message = '') {
const playing = !audio.paused && !audio.ended;
button.setAttribute('aria-pressed', String(playing));
button.textContent = pending ? 'Запускаем звук…'
: playing ? 'Приостановить звук'
: audio.ended ? 'Послушать ещё раз'
: audio.currentTime > 0 ? 'Продолжить звук'
: 'Включить звук';
if (status) status.textContent = message;
}
async function start({ automatic = false } = {}) {
if (destroyed || pending || (!audio.paused && !audio.ended)) return false;
if (automatic && (manuallyPaused || audio.ended)) return false;
if (!automatic) {
manuallyPaused = false;
remember('enabled');
}
const thisRequest = ++requestVersion;
pending = true;
render();
if (audio.ended) audio.currentTime = 0;
try {
// play() runs before the first await so click activation is not discarded.
await audio.play();
if (destroyed || thisRequest !== requestVersion || manuallyPaused) {
audio.pause();
return false;
}
render();
return true;
} catch (error) {
if (destroyed || thisRequest !== requestVersion) return false;
const message = error.name === 'NotAllowedError'
? 'Нажмите «Включить звук», чтобы начать озвучку.'
: 'Звук пока недоступен. Содержимое страницы можно читать без него.';
render(message);
return false;
} finally {
if (thisRequest === requestVersion) {
pending = false;
// Preserve a useful failure status while updating the button.
render(status?.textContent || '');
}
}
}
function pause({ userInitiated = true } = {}) {
requestVersion += 1;
pending = false;
firstScrollAttempted = true;
if (userInitiated) {
manuallyPaused = true;
remember('paused');
}
audio.pause();
render();
}
button.addEventListener('click', () => {
if (pending || (!audio.paused && !audio.ended)) pause();
else void start();
}, options);
audio.addEventListener('playing', () => render(), options);
audio.addEventListener('pause', () => render(), options);
audio.addEventListener('ended', () => render('Озвучка завершена.'), options);
audio.addEventListener('error', () => render('Аудиофайл не загрузился. Проверьте адрес и формат файла.'), options);
if (attemptOnFirstScroll) {
window.addEventListener('scroll', () => {
if (firstScrollAttempted || manuallyPaused || Math.abs(window.scrollY - initialScrollY) < 8) return;
firstScrollAttempted = true;
// Optional single attempt; a scroll event does not guarantee autoplay permission.
void start({ automatic: true });
}, { ...options, passive: true });
}
document.addEventListener('visibilitychange', () => {
if (document.hidden) pause({ userInitiated: false });
// Returning to the tab does not unexpectedly restart the narration.
}, options);
window.addEventListener('pagehide', () => pause({ userInitiated: false }), options);
render();
return {
start,
pause,
destroy() {
destroyed = true;
pause({ userInitiated: false });
listeners.abort();
},
};
}