/** Optional title theme music on detail pages, faded in and out. */ import { useSession } from '../app/session'; import { useSettings } from '../app/settings'; let audio: HTMLAudioElement | null = null; let current = ''; let fade: ReturnType | null = null; function fadeTo(target: number, done?: () => void) { if (!audio) return; if (fade) clearInterval(fade); const a = audio; fade = setInterval(() => { const step = Math.max(0.002, target / 25, a.volume / 25); if (Math.abs(a.volume - target) <= step) { a.volume = target; clearInterval(fade!); fade = null; done?.(); } else a.volume += a.volume < target ? step : -step; }, 40); } /** * Theme songs are mastered far louder than a film's dialogue, so the setting * follows a square law and scales with the player's own volume: the default * 30% sits around -21 dB, under the show it introduces. */ function themeGain() { const { themeVolume, volume } = useSettings.getState(); return Math.pow(themeVolume / 100, 2) * Math.pow(Math.min(100, volume) / 100, 2); } export function playThemeMusic(path: string) { const prefs = useSettings.getState(); const server = useSession.getState().server; if (!prefs.themeMusic || !path || !server || /player-(open|mini)/.test(document.documentElement.className)) return; if (path === current && audio && !audio.paused) return; stopThemeMusic(true); current = path; audio = new Audio(server.signed(path)); audio.volume = 0; audio.loop = false; audio.play().then(() => fadeTo(themeGain()), () => {}); } export function stopThemeMusic(immediate = false) { current = ''; if (!audio) return; const a = audio; audio = null; if (immediate) { a.pause(); return; } const prev = audio; audio = a; fadeTo(0, () => { a.pause(); if (audio === a) audio = prev; }); }