302 lines
8.6 KiB
JavaScript
302 lines
8.6 KiB
JavaScript
// Аудио-движок презентации: фоновая музыка, эффекты, ducking и раздельные громкости.
|
|
// Работает на клиенте; команды синхронизируются докладчиком через WebSocket.
|
|
(function () {
|
|
const DUCK = 0.22; // насколько приглушается фон, пока играет эффект
|
|
const FADE_IN = 500;
|
|
const FADE_OUT = 380;
|
|
|
|
function clamp(value, fallback = 0) {
|
|
const n = Number(value);
|
|
if (!Number.isFinite(n)) return fallback;
|
|
return Math.max(0, Math.min(1, n));
|
|
}
|
|
|
|
function fadeTo(audio, target, ms) {
|
|
if (!audio) return;
|
|
const to = clamp(target, 0);
|
|
if (audio._fadeTimer) clearInterval(audio._fadeTimer);
|
|
const from = audio.volume;
|
|
const start = performance.now();
|
|
const duration = Math.max(1, ms || 1);
|
|
if (Math.abs(from - to) < 0.005) {
|
|
audio.volume = to;
|
|
return;
|
|
}
|
|
audio._fadeTimer = setInterval(() => {
|
|
const t = Math.min(1, (performance.now() - start) / duration);
|
|
const eased = t * t * (3 - 2 * t);
|
|
audio.volume = clamp(from + (to - from) * eased, 0);
|
|
if (t >= 1) {
|
|
clearInterval(audio._fadeTimer);
|
|
audio._fadeTimer = null;
|
|
}
|
|
}, 28);
|
|
}
|
|
|
|
function createAudioController(options = {}) {
|
|
const onBlocked = typeof options.onBlocked === 'function' ? options.onBlocked : () => {};
|
|
const onState = typeof options.onState === 'function' ? options.onState : () => {};
|
|
const onEnded = typeof options.onEnded === 'function' ? options.onEnded : () => {};
|
|
|
|
const bgm = new Audio();
|
|
bgm.preload = 'auto';
|
|
bgm.loop = true;
|
|
|
|
const effects = new Map(); // id -> { audio, volume, loop }
|
|
let musicSrc = '';
|
|
let musicPlaying = false;
|
|
let bgmLevel = 0.5;
|
|
let sfxLevel = 0.8;
|
|
let unlocked = false;
|
|
let blockedNotified = false;
|
|
let pending = []; // команды, которые не удалось запустить до разблокировки звука
|
|
|
|
function activeEffects() {
|
|
let count = 0;
|
|
effects.forEach((entry) => {
|
|
if (!entry.audio.paused && !entry.audio.ended) count += 1;
|
|
});
|
|
return count;
|
|
}
|
|
|
|
function bgmTarget() {
|
|
if (!musicPlaying) return 0;
|
|
return clamp(bgmLevel * (activeEffects() > 0 ? DUCK : 1), 0);
|
|
}
|
|
|
|
function updateDucking() {
|
|
fadeTo(bgm, bgmTarget(), 420);
|
|
}
|
|
|
|
function state() {
|
|
return { musicSrc, musicPlaying, bgm: bgmLevel, sfx: sfxLevel };
|
|
}
|
|
|
|
function emitState() {
|
|
onState(state());
|
|
}
|
|
|
|
function notifyBlocked() {
|
|
if (blockedNotified) return;
|
|
blockedNotified = true;
|
|
onBlocked();
|
|
}
|
|
|
|
function clearBlocked() {
|
|
blockedNotified = false;
|
|
}
|
|
|
|
function safePlay(audio, onFail) {
|
|
const promise = audio.play();
|
|
if (promise && typeof promise.catch === 'function') {
|
|
promise.catch((err) => {
|
|
// Autoplay policy: ждём клика пользователя
|
|
if (err && (err.name === 'NotAllowedError' || err.name === 'NotSupportedError' || err.name === 'AbortError')) {
|
|
notifyBlocked();
|
|
if (typeof onFail === 'function') onFail(err);
|
|
}
|
|
});
|
|
}
|
|
return promise;
|
|
}
|
|
|
|
function setMusicSource(src) {
|
|
const next = String(src || '');
|
|
if (next === musicSrc && bgm.src) return;
|
|
musicSrc = next;
|
|
if (next) {
|
|
bgm.src = next;
|
|
bgm.load();
|
|
} else {
|
|
bgm.pause();
|
|
bgm.removeAttribute('src');
|
|
bgm.load();
|
|
}
|
|
}
|
|
|
|
function playMusic(src) {
|
|
if (src) setMusicSource(src);
|
|
if (!musicSrc) return;
|
|
musicPlaying = true;
|
|
bgm.loop = true;
|
|
if (bgm.volume === 0) bgm.volume = 0;
|
|
safePlay(bgm, () => {
|
|
// Попробуем ещё раз, когда пользователь разблокирует звук
|
|
pending.push({ action: 'music', src: musicSrc, play: true });
|
|
});
|
|
setTimeout(updateDucking, 60);
|
|
emitState();
|
|
}
|
|
|
|
function stopMusic() {
|
|
musicPlaying = false;
|
|
fadeTo(bgm, 0, FADE_OUT);
|
|
setTimeout(() => {
|
|
if (!musicPlaying) bgm.pause();
|
|
}, FADE_OUT + 30);
|
|
emitState();
|
|
}
|
|
|
|
function playEffect(command) {
|
|
const id = String(command.id || command.audioId || '');
|
|
if (!id) return;
|
|
const existing = effects.get(id);
|
|
if (existing) {
|
|
try {
|
|
existing.audio.pause();
|
|
} catch (e) {
|
|
/* noop */
|
|
}
|
|
effects.delete(id);
|
|
}
|
|
if (!command.src) return;
|
|
|
|
const audio = new Audio();
|
|
audio.preload = 'auto';
|
|
audio.src = command.src;
|
|
audio.loop = !!command.loop;
|
|
audio.volume = 0;
|
|
const volume = clamp(command.volume, 0.8);
|
|
const entry = { audio, volume, loop: !!command.loop };
|
|
effects.set(id, entry);
|
|
|
|
audio.addEventListener('ended', () => {
|
|
if (effects.get(id) === entry) effects.delete(id);
|
|
updateDucking();
|
|
emitState();
|
|
onEnded(id);
|
|
});
|
|
|
|
safePlay(audio, () => {
|
|
pending.push({ action: 'play', id, src: command.src, loop: !!command.loop, volume });
|
|
});
|
|
fadeTo(audio, clamp(volume * sfxLevel, 0), FADE_IN);
|
|
updateDucking();
|
|
emitState();
|
|
}
|
|
|
|
function stopEffect(id) {
|
|
const key = String(id || '');
|
|
if (!key) return;
|
|
const entry = effects.get(key);
|
|
if (!entry) return;
|
|
effects.delete(key);
|
|
const audio = entry.audio;
|
|
fadeTo(audio, 0, FADE_OUT);
|
|
setTimeout(() => {
|
|
try {
|
|
audio.pause();
|
|
} catch (e) {
|
|
/* noop */
|
|
}
|
|
}, FADE_OUT + 30);
|
|
updateDucking();
|
|
emitState();
|
|
}
|
|
|
|
function stopAllEffects() {
|
|
effects.forEach((entry) => {
|
|
const audio = entry.audio;
|
|
fadeTo(audio, 0, FADE_OUT);
|
|
setTimeout(() => {
|
|
try {
|
|
audio.pause();
|
|
} catch (e) {
|
|
/* noop */
|
|
}
|
|
}, FADE_OUT + 30);
|
|
});
|
|
effects.clear();
|
|
updateDucking();
|
|
emitState();
|
|
}
|
|
|
|
function applyVolumes(bgmValue, sfxValue) {
|
|
bgmLevel = clamp(bgmValue, bgmLevel);
|
|
sfxLevel = clamp(sfxValue, sfxLevel);
|
|
updateDucking();
|
|
effects.forEach((entry) => {
|
|
fadeTo(entry.audio, clamp(entry.volume * sfxLevel, 0), 220);
|
|
});
|
|
emitState();
|
|
}
|
|
|
|
function applyCommand(command) {
|
|
if (!command || typeof command !== 'object') return;
|
|
switch (command.action) {
|
|
case 'music':
|
|
if (typeof command.src === 'string' && command.src) setMusicSource(command.src);
|
|
if (command.play === false) stopMusic();
|
|
else playMusic();
|
|
break;
|
|
case 'musicStop':
|
|
stopMusic();
|
|
break;
|
|
case 'play':
|
|
playEffect(command);
|
|
break;
|
|
case 'stop':
|
|
if (command.id === '*' || command.all) stopAllEffects();
|
|
else stopEffect(command.id);
|
|
break;
|
|
case 'effectVolume': {
|
|
const entry = effects.get(String(command.id || ''));
|
|
if (entry) {
|
|
entry.volume = clamp(command.volume, entry.volume);
|
|
fadeTo(entry.audio, clamp(entry.volume * sfxLevel, 0), 220);
|
|
}
|
|
break;
|
|
}
|
|
case 'volumes':
|
|
applyVolumes(command.bgm, command.sfx);
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
emitState();
|
|
}
|
|
|
|
// Разблокировка звука по клику пользователя (autoplay policy браузеров)
|
|
function unlock() {
|
|
unlocked = true;
|
|
clearBlocked();
|
|
const silent = new Audio(
|
|
'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAgD4AAAB9AAACABAAZGF0YQAAAAA='
|
|
);
|
|
silent.volume = 0.001;
|
|
silent.play().catch(() => {});
|
|
if (musicPlaying && musicSrc) safePlay(bgm);
|
|
const queue = pending.splice(0);
|
|
queue.forEach((command) => applyCommand(command));
|
|
emitState();
|
|
return true;
|
|
}
|
|
|
|
function getPlayingEffectIds() {
|
|
const ids = [];
|
|
effects.forEach((entry, id) => {
|
|
if (!entry.audio.paused) ids.push(id);
|
|
});
|
|
return ids;
|
|
}
|
|
|
|
return {
|
|
applyCommand,
|
|
applyVolumes,
|
|
playMusic,
|
|
stopMusic,
|
|
playEffect,
|
|
stopEffect,
|
|
stopAllEffects,
|
|
setBgmLevel: (value) => applyVolumes(value, sfxLevel),
|
|
setSfxLevel: (value) => applyVolumes(bgmLevel, value),
|
|
getState: state,
|
|
getPlayingEffectIds,
|
|
isUnlocked: () => unlocked,
|
|
unlock,
|
|
};
|
|
}
|
|
|
|
window.createAudioController = createAudioController;
|
|
})();
|