import { getDevicePref } from './device-prefs.js'; let audioContext = null; let audioUnlocked = false; function audioContextConstructor() { return globalThis.window?.AudioContext || globalThis.window?.webkitAudioContext || null; } export async function unlockDmAudio() { const AudioContextConstructor = audioContextConstructor(); if (!AudioContextConstructor) return { ok: false, code: 'unsupported' }; try { if (!audioContext) audioContext = new AudioContextConstructor(); if (audioContext.state === 'suspended') await audioContext.resume(); audioUnlocked = audioContext.state === 'running'; return audioUnlocked ? { ok: true, code: 'ready', state: audioContext.state } : { ok: false, code: 'blocked', state: audioContext.state }; } catch (error) { return { ok: false, code: 'error', state: audioContext?.state || 'unknown', error }; } } function playSignal({ extended = false } = {}) { if (!audioUnlocked || !audioContext || audioContext.state !== 'running') { return { ok: false, code: 'blocked', state: audioContext?.state || 'unknown' }; } try { const now = audioContext.currentTime; const gain = audioContext.createGain(); gain.connect(audioContext.destination); gain.gain.setValueAtTime(0.0001, now); const pulse = (offsetSec, freqHz, durationSec, peakGain) => { const osc = audioContext.createOscillator(); osc.type = 'sine'; osc.frequency.setValueAtTime(freqHz, now + offsetSec); osc.connect(gain); gain.gain.exponentialRampToValueAtTime(peakGain, now + offsetSec + 0.01); gain.gain.exponentialRampToValueAtTime(0.0001, now + offsetSec + durationSec); osc.start(now + offsetSec); osc.stop(now + offsetSec + durationSec + 0.02); }; if (extended) { pulse(0, 880, 0.18, 0.032); pulse(0.24, 1174, 0.2, 0.026); pulse(0.52, 1567, 0.24, 0.02); } else { pulse(0, 1046, 0.12, 0.028); pulse(0.17, 1318, 0.14, 0.022); } return { ok: true, code: 'played', state: audioContext.state }; } catch (error) { return { ok: false, code: 'error', state: audioContext.state, error }; } } export async function playDmSignal(options = {}) { if (getDevicePref('dmSound', true) === false) return { ok: false, code: 'disabled' }; const unlocked = await unlockDmAudio(); return unlocked.ok ? playSignal(options) : unlocked; } export async function testDmSound() { const unlocked = await unlockDmAudio(); if (!unlocked.ok) return unlocked; return playSignal({ extended: false }); }