/** * Звуковые эффекты: файлы, а на случай их отсутствия — синтез. * * Положите в content/sfx/ файл с нужным именем (correct.mp3, buzz.wav, …) — * сервер сам отдаст его как /sfx/…, и он заменит встроенный звук. Ничего * настраивать не нужно: имя файла и есть настройка. * * Синтез остаётся запасным вариантом, чтобы игра звучала и на чистом проекте. */ const STORAGE_KEY = 'quiz:sound' export const SFX_NAMES = ['open', 'buzz', 'correct', 'wrong', 'tick', 'end'] as const export type SfxName = (typeof SFX_NAMES)[number] let context: AudioContext | null = null let enabled = false const files = new Map() const players = new Map() export function preferredSound(): boolean { try { return localStorage.getItem(STORAGE_KEY) === '1' } catch { return false } } export function soundEnabled(): boolean { return enabled } export function availableSfx(): SfxName[] { return [...files.keys()] } /** * Спрашивает у сервера, какие эффекты заменены файлами, и заранее их грузит. * Ошибка сети не критична: останется синтез. */ export async function loadSfx(): Promise { try { const response = await fetch('/api/sfx') if (!response.ok) return const data = (await response.json()) as { files?: Record } for (const name of SFX_NAMES) { const url = data.files?.[name] if (!url) continue files.set(name, url) const audio = new Audio() audio.src = url audio.preload = 'auto' audio.volume = 0.85 players.set(name, audio) } } catch { // Сервер мог быть ещё не готов — останется синтез. } } export async function enableSound(): Promise { if (typeof window === 'undefined') return false try { if (!context) context = new AudioContext() if (context.state === 'suspended') await context.resume() enabled = context.state === 'running' localStorage.setItem(STORAGE_KEY, enabled ? '1' : '0') } catch { enabled = false } return enabled } export function disableSound(): void { enabled = false try { localStorage.setItem(STORAGE_KEY, '0') } catch { // Приватный режим — не страшно. } } // ─── Синтез (запасной вариант) ───────────────────────────────────────────── interface ToneOptions { frequency: number duration: number type?: OscillatorType gain?: number delay?: number sweepTo?: number } function tone(options: ToneOptions): void { if (!context || context.state !== 'running') return const start = context.currentTime + (options.delay ?? 0) const oscillator = context.createOscillator() const amp = context.createGain() oscillator.type = options.type ?? 'sine' oscillator.frequency.setValueAtTime(options.frequency, start) if (options.sweepTo) { oscillator.frequency.exponentialRampToValueAtTime(options.sweepTo, start + options.duration) } const level = options.gain ?? 0.14 amp.gain.setValueAtTime(0.0001, start) amp.gain.exponentialRampToValueAtTime(level, start + 0.012) amp.gain.exponentialRampToValueAtTime(0.0001, start + options.duration) oscillator.connect(amp) amp.connect(context.destination) oscillator.start(start) oscillator.stop(start + options.duration + 0.03) } const SYNTH: Record void> = { open: () => tone({ frequency: 520, sweepTo: 880, duration: 0.12, type: 'triangle', gain: 0.1 }), buzz: () => tone({ frequency: 190, sweepTo: 120, duration: 0.16, type: 'square', gain: 0.12 }), correct: () => { tone({ frequency: 660, duration: 0.16, type: 'sine', gain: 0.16 }) tone({ frequency: 990, duration: 0.24, type: 'sine', gain: 0.14, delay: 0.12 }) }, wrong: () => tone({ frequency: 240, sweepTo: 110, duration: 0.38, type: 'sawtooth', gain: 0.1 }), tick: () => tone({ frequency: 1200, duration: 0.045, type: 'sine', gain: 0.05 }), end: () => { for (const [index, frequency] of [523, 659, 784].entries()) { tone({ frequency, duration: 0.5, type: 'sine', gain: 0.1, delay: index * 0.09 }) } }, } // ─── Воспроизведение ─────────────────────────────────────────────────────── function play(name: SfxName): void { if (!enabled) return const player = players.get(name) if (player) { try { player.currentTime = 0 void player.play() return } catch { // Файл не проигрался — не повод молчать, сыграем синтезом. } } SYNTH[name]() } export const sfx = { open: (): void => play('open'), buzz: (): void => play('buzz'), correct: (): void => play('correct'), wrong: (): void => play('wrong'), tick: (): void => play('tick'), end: (): void => play('end'), }