1
votes

I have been looking at the Web Audio API and am not able to get the audio gain to work. I have a fiddle set up here, so you can understand the application of the function: http://jsfiddle.net/mnu70gy3/

I am hoping to dynamically create a tone on a click event, but am not able to have that tone fade out. Below is the relevant code:

var audioCtx = new AudioContext();
var osc = {};  // set up an object for all the oscillators
var gainNodes = {};  // set up an object for all the gains
var now;
function tone(id,freq) {

    // create osc / set gain / connect osc
    gainNodes.id = audioCtx.createGain();
    osc.id = audioCtx.createOscillator();
    osc.id.connect(audioCtx.destination);

    // set frequency
    osc.id.frequency.value = freq;

    // set gain at 1 and fade to 0 in one second
    gainNodes.id.gain.value = 1.0;
    gainNodes.id.gain.setValueAtTime(0, audioCtx.currentTime + 1);

    // start and connect
    osc.id.start(0);
    osc.id.connect(audioCtx.destination); 
}

Any thoughts on if this can be done?

2
Have you seen this? Also includes the code (well commented) on how to vinculate with a slider. - lalengua

2 Answers

2
votes

In your code you connect oscillator to the destination twice. Instead of connecting oscillator -> gain -> destination

gainNodes.id = audioCtx.createGain();
osc.id = audioCtx.createOscillator();
osc.id.connect(gainNodes.id);

// set frequency and gain
osc.id.frequency.value = freq;
gainNodes.id.gain.value = 1.0;
gainNodes.id.gain.setValueAtTime(0, audioCtx.currentTime + 1);

// start and connect
osc.id.start(0);
gainNodes.id.connect(audioCtx.destination);
1
votes

You need to disconnect your audioCtx.destination when you click on a tile again.

https://jsfiddle.net/2dyq2ajw/

function dismissTone(id,freq) {
    gainNodes.id.gain.value = 0; 
    osc.id.disconnect(audioCtx.destination);
}

    if($(this).hasClass('xx'))
        tone(thisId,thisFreq);
    else
        dismissTone(thisId,thisFreq);