Home:ALL Converter>Web Audio Api, setting the gain

Web Audio Api, setting the gain

Ask Time:2015-06-01T09:01:59         Author:superUntitled

Json Formatter

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?

Author:superUntitled,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/30564330/web-audio-api-setting-the-gain
Kirill Slatin :

In your code you connect oscillator to the destination twice.\nInstead of connecting oscillator -> gain -> destination\n\ngainNodes.id = audioCtx.createGain();\nosc.id = audioCtx.createOscillator();\nosc.id.connect(gainNodes.id);\n\n// set frequency and gain\nosc.id.frequency.value = freq;\ngainNodes.id.gain.value = 1.0;\ngainNodes.id.gain.setValueAtTime(0, audioCtx.currentTime + 1);\n\n// start and connect\nosc.id.start(0);\ngainNodes.id.connect(audioCtx.destination);\n",
2015-06-01T01:16:03
yy