16 lines
1.2 KiB
JavaScript
16 lines
1.2 KiB
JavaScript
let ctx;let enabled=true;try{enabled=localStorage.getItem('hex-sound')!=='off';}catch{}
|
|
export function soundEnabled(){return enabled;}
|
|
export function toggleSound(){enabled=!enabled;try{localStorage.setItem('hex-sound',enabled?'on':'off');}catch{}return enabled;}
|
|
function tone(freq,when,duration,volume=.045,type='sine'){
|
|
if(!enabled||!ctx||ctx.state!=='running')return;const o=ctx.createOscillator(),g=ctx.createGain(),t=ctx.currentTime+when;o.type=type;o.frequency.setValueAtTime(freq,t);g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(volume,t+.008);g.gain.exponentialRampToValueAtTime(.001,t+duration);o.connect(g);g.connect(ctx.destination);o.start(t);o.stop(t+duration+.02);
|
|
}
|
|
export function unlockAudio(){try{ctx??=new (window.AudioContext||window.webkitAudioContext)();if(ctx.state==='suspended')ctx.resume().catch(()=>{});}catch{}}
|
|
export function playSound(name){
|
|
if(name==='win'){[523,659,784].forEach((f,i)=>tone(f,.3+i*.19,.3,.055));return;}
|
|
if(name==='hit'){tone(145,0,.12,.075,'triangle');tone(85,.025,.16,.04);return;}
|
|
if(name==='rotate'){tone(330,0,.09);tone(440,.075,.13);return;}
|
|
if(name==='exit'){tone(660,0,.1);tone(880,.065,.13);return;}
|
|
if(name==='lose'){tone(294,0,.2);tone(220,.17,.25);return;}
|
|
tone(480,0,.06,.023);
|
|
}
|