Репозитории /
Promptly /
public/js/audio-controller.js
audio-controller.js
| 1 | // Аудио-движок презентации: фоновая музыка, эффекты, ducking и раздельные громкости. |
| 2 | // Работает на клиенте; команды синхронизируются докладчиком через WebSocket. |
| 3 | (function () { |
| 4 | const DUCK = 0.22; // насколько приглушается фон, пока играет эффект |
| 5 | const FADE_IN = 500; |
| 6 | const FADE_OUT = 380; |
| 7 | |
| 8 | function clamp(value, fallback = 0) { |
| 9 | const n = Number(value); |
| 10 | if (!Number.isFinite(n)) return fallback; |
| 11 | return Math.max(0, Math.min(1, n)); |
| 12 | } |
| 13 | |
| 14 | function fadeTo(audio, target, ms) { |
| 15 | if (!audio) return; |
| 16 | const to = clamp(target, 0); |
| 17 | if (audio._fadeTimer) clearInterval(audio._fadeTimer); |
| 18 | const from = audio.volume; |
| 19 | const start = performance.now(); |
| 20 | const duration = Math.max(1, ms || 1); |
| 21 | if (Math.abs(from - to) < 0.005) { |
| 22 | audio.volume = to; |
| 23 | return; |
| 24 | } |
| 25 | audio._fadeTimer = setInterval(() => { |
| 26 | const t = Math.min(1, (performance.now() - start) / duration); |
| 27 | const eased = t * t * (3 - 2 * t); |
| 28 | audio.volume = clamp(from + (to - from) * eased, 0); |
| 29 | if (t >= 1) { |
| 30 | clearInterval(audio._fadeTimer); |
| 31 | audio._fadeTimer = null; |
| 32 | } |
| 33 | }, 28); |
| 34 | } |
| 35 | |
| 36 | function createAudioController(options = {}) { |
| 37 | const onBlocked = typeof options.onBlocked === 'function' ? options.onBlocked : () => {}; |
| 38 | const onState = typeof options.onState === 'function' ? options.onState : () => {}; |
| 39 | const onEnded = typeof options.onEnded === 'function' ? options.onEnded : () => {}; |
| 40 | |
| 41 | const bgm = new Audio(); |
| 42 | bgm.preload = 'auto'; |
| 43 | bgm.loop = true; |
| 44 | |
| 45 | const effects = new Map(); // id -> { audio, volume, loop } |
| 46 | let musicSrc = ''; |
| 47 | let musicPlaying = false; |
| 48 | let bgmLevel = 0.5; |
| 49 | let sfxLevel = 0.8; |
| 50 | let unlocked = false; |
| 51 | let blockedNotified = false; |
| 52 | let pending = []; // команды, которые не удалось запустить до разблокировки звука |
| 53 | |
| 54 | function activeEffects() { |
| 55 | let count = 0; |
| 56 | effects.forEach((entry) => { |
| 57 | if (!entry.audio.paused && !entry.audio.ended) count += 1; |
| 58 | }); |
| 59 | return count; |
| 60 | } |
| 61 | |
| 62 | function bgmTarget() { |
| 63 | if (!musicPlaying) return 0; |
| 64 | return clamp(bgmLevel * (activeEffects() > 0 ? DUCK : 1), 0); |
| 65 | } |
| 66 | |
| 67 | function updateDucking() { |
| 68 | fadeTo(bgm, bgmTarget(), 420); |
| 69 | } |
| 70 | |
| 71 | function state() { |
| 72 | return { musicSrc, musicPlaying, bgm: bgmLevel, sfx: sfxLevel }; |
| 73 | } |
| 74 | |
| 75 | function emitState() { |
| 76 | onState(state()); |
| 77 | } |
| 78 | |
| 79 | function notifyBlocked() { |
| 80 | if (blockedNotified) return; |
| 81 | blockedNotified = true; |
| 82 | onBlocked(); |
| 83 | } |
| 84 | |
| 85 | function clearBlocked() { |
| 86 | blockedNotified = false; |
| 87 | } |
| 88 | |
| 89 | function safePlay(audio, onFail) { |
| 90 | const promise = audio.play(); |
| 91 | if (promise && typeof promise.catch === 'function') { |
| 92 | promise.catch((err) => { |
| 93 | // Autoplay policy: ждём клика пользователя |
| 94 | if (err && (err.name === 'NotAllowedError' || err.name === 'NotSupportedError' || err.name === 'AbortError')) { |
| 95 | notifyBlocked(); |
| 96 | if (typeof onFail === 'function') onFail(err); |
| 97 | } |
| 98 | }); |
| 99 | } |
| 100 | return promise; |
| 101 | } |
| 102 | |
| 103 | function setMusicSource(src) { |
| 104 | const next = String(src || ''); |
| 105 | if (next === musicSrc && bgm.src) return; |
| 106 | musicSrc = next; |
| 107 | if (next) { |
| 108 | bgm.src = next; |
| 109 | bgm.load(); |
| 110 | } else { |
| 111 | bgm.pause(); |
| 112 | bgm.removeAttribute('src'); |
| 113 | bgm.load(); |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | function playMusic(src) { |
| 118 | if (src) setMusicSource(src); |
| 119 | if (!musicSrc) return; |
| 120 | musicPlaying = true; |
| 121 | bgm.loop = true; |
| 122 | if (bgm.volume === 0) bgm.volume = 0; |
| 123 | safePlay(bgm, () => { |
| 124 | // Попробуем ещё раз, когда пользователь разблокирует звук |
| 125 | pending.push({ action: 'music', src: musicSrc, play: true }); |
| 126 | }); |
| 127 | setTimeout(updateDucking, 60); |
| 128 | emitState(); |
| 129 | } |
| 130 | |
| 131 | function stopMusic() { |
| 132 | musicPlaying = false; |
| 133 | fadeTo(bgm, 0, FADE_OUT); |
| 134 | setTimeout(() => { |
| 135 | if (!musicPlaying) bgm.pause(); |
| 136 | }, FADE_OUT + 30); |
| 137 | emitState(); |
| 138 | } |
| 139 | |
| 140 | function playEffect(command) { |
| 141 | const id = String(command.id || command.audioId || ''); |
| 142 | if (!id) return; |
| 143 | const existing = effects.get(id); |
| 144 | if (existing) { |
| 145 | try { |
| 146 | existing.audio.pause(); |
| 147 | } catch (e) { |
| 148 | /* noop */ |
| 149 | } |
| 150 | effects.delete(id); |
| 151 | } |
| 152 | if (!command.src) return; |
| 153 | |
| 154 | const audio = new Audio(); |
| 155 | audio.preload = 'auto'; |
| 156 | audio.src = command.src; |
| 157 | audio.loop = !!command.loop; |
| 158 | audio.volume = 0; |
| 159 | const volume = clamp(command.volume, 0.8); |
| 160 | const entry = { audio, volume, loop: !!command.loop }; |
| 161 | effects.set(id, entry); |
| 162 | |
| 163 | audio.addEventListener('ended', () => { |
| 164 | if (effects.get(id) === entry) effects.delete(id); |
| 165 | updateDucking(); |
| 166 | emitState(); |
| 167 | onEnded(id); |
| 168 | }); |
| 169 | |
| 170 | safePlay(audio, () => { |
| 171 | pending.push({ action: 'play', id, src: command.src, loop: !!command.loop, volume }); |
| 172 | }); |
| 173 | fadeTo(audio, clamp(volume * sfxLevel, 0), FADE_IN); |
| 174 | updateDucking(); |
| 175 | emitState(); |
| 176 | } |
| 177 | |
| 178 | function stopEffect(id) { |
| 179 | const key = String(id || ''); |
| 180 | if (!key) return; |
| 181 | const entry = effects.get(key); |
| 182 | if (!entry) return; |
| 183 | effects.delete(key); |
| 184 | const audio = entry.audio; |
| 185 | fadeTo(audio, 0, FADE_OUT); |
| 186 | setTimeout(() => { |
| 187 | try { |
| 188 | audio.pause(); |
| 189 | } catch (e) { |
| 190 | /* noop */ |
| 191 | } |
| 192 | }, FADE_OUT + 30); |
| 193 | updateDucking(); |
| 194 | emitState(); |
| 195 | } |
| 196 | |
| 197 | function stopAllEffects() { |
| 198 | effects.forEach((entry) => { |
| 199 | const audio = entry.audio; |
| 200 | fadeTo(audio, 0, FADE_OUT); |
| 201 | setTimeout(() => { |
| 202 | try { |
| 203 | audio.pause(); |
| 204 | } catch (e) { |
| 205 | /* noop */ |
| 206 | } |
| 207 | }, FADE_OUT + 30); |
| 208 | }); |
| 209 | effects.clear(); |
| 210 | updateDucking(); |
| 211 | emitState(); |
| 212 | } |
| 213 | |
| 214 | function applyVolumes(bgmValue, sfxValue) { |
| 215 | bgmLevel = clamp(bgmValue, bgmLevel); |
| 216 | sfxLevel = clamp(sfxValue, sfxLevel); |
| 217 | updateDucking(); |
| 218 | effects.forEach((entry) => { |
| 219 | fadeTo(entry.audio, clamp(entry.volume * sfxLevel, 0), 220); |
| 220 | }); |
| 221 | emitState(); |
| 222 | } |
| 223 | |
| 224 | function applyCommand(command) { |
| 225 | if (!command || typeof command !== 'object') return; |
| 226 | switch (command.action) { |
| 227 | case 'music': |
| 228 | if (typeof command.src === 'string' && command.src) setMusicSource(command.src); |
| 229 | if (command.play === false) stopMusic(); |
| 230 | else playMusic(); |
| 231 | break; |
| 232 | case 'musicStop': |
| 233 | stopMusic(); |
| 234 | break; |
| 235 | case 'play': |
| 236 | playEffect(command); |
| 237 | break; |
| 238 | case 'stop': |
| 239 | if (command.id === '*' || command.all) stopAllEffects(); |
| 240 | else stopEffect(command.id); |
| 241 | break; |
| 242 | case 'effectVolume': { |
| 243 | const entry = effects.get(String(command.id || '')); |
| 244 | if (entry) { |
| 245 | entry.volume = clamp(command.volume, entry.volume); |
| 246 | fadeTo(entry.audio, clamp(entry.volume * sfxLevel, 0), 220); |
| 247 | } |
| 248 | break; |
| 249 | } |
| 250 | case 'volumes': |
| 251 | applyVolumes(command.bgm, command.sfx); |
| 252 | break; |
| 253 | default: |
| 254 | break; |
| 255 | } |
| 256 | emitState(); |
| 257 | } |
| 258 | |
| 259 | // Разблокировка звука по клику пользователя (autoplay policy браузеров) |
| 260 | function unlock() { |
| 261 | unlocked = true; |
| 262 | clearBlocked(); |
| 263 | const silent = new Audio( |
| 264 | 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAgD4AAAB9AAACABAAZGF0YQAAAAA=' |
| 265 | ); |
| 266 | silent.volume = 0.001; |
| 267 | silent.play().catch(() => {}); |
| 268 | if (musicPlaying && musicSrc) safePlay(bgm); |
| 269 | const queue = pending.splice(0); |
| 270 | queue.forEach((command) => applyCommand(command)); |
| 271 | emitState(); |
| 272 | return true; |
| 273 | } |
| 274 | |
| 275 | function getPlayingEffectIds() { |
| 276 | const ids = []; |
| 277 | effects.forEach((entry, id) => { |
| 278 | if (!entry.audio.paused) ids.push(id); |
| 279 | }); |
| 280 | return ids; |
| 281 | } |
| 282 | |
| 283 | return { |
| 284 | applyCommand, |
| 285 | applyVolumes, |
| 286 | playMusic, |
| 287 | stopMusic, |
| 288 | playEffect, |
| 289 | stopEffect, |
| 290 | stopAllEffects, |
| 291 | setBgmLevel: (value) => applyVolumes(value, sfxLevel), |
| 292 | setSfxLevel: (value) => applyVolumes(bgmLevel, value), |
| 293 | getState: state, |
| 294 | getPlayingEffectIds, |
| 295 | isUnlocked: () => unlocked, |
| 296 | unlock, |
| 297 | }; |
| 298 | } |
| 299 | |
| 300 | window.createAudioController = createAudioController; |
| 301 | })(); |