Button with Audio Feedback
by NunoMira
HTML
<button id="clicksound" data-active="false">Sem som</button>
JavaScript
var ctx = new AudioContext();
var clicksound = document.getElementById('clicksound');
clickme.addEventListener('click',soundHandler);
function soundHandler(e) {
if (e.path[0].dataset.active === 'false') {
e.path[0].dataset.active = 'true';
e.srcElement.textContent = 'Com som'
}
else {
e.path[0].dataset.active = 'false';
e.srcElement.textContent = 'Sem som'
playBeep();
}
}
function playBeep() {
var o = ctx.createOscillator(), g = ctx.createGain(), playLength = 0.07;
o.type = 'sine';
o.frequency.value = 261.63;
o.start(ctx.currentTime);
o.stop(ctx.currentTime + playLength);
g.gain.value = 0.5;
g.gain.setValueAtTime(1,ctx.currentTime + playLength - 0.2);
g.gain.linearRampToValueAtTime(0,ctx.currentTime + playLength);
o.connect(g);
g.connect(ctx.destination);
}