Search code examples
audioweb-audio-api

why GainNode connections are not workinng?


I'm using Web audio API to get the frequency data from a sound file. Basically I have implemented the code showed in this example what I want to add it is a gainNode so I can control the volume in any place of my code, but something is wrong with the connections I have made, everything else works just fine.

The volume part is the only thing I've changed from the original code:

request.onload = function() {
    context.decodeAudioData(
        request.response,
        function(buffer) {
            if(!buffer) {
                $('#info').text('Error decoding file data');
                return;
            }
            
            sourceJs = context.createJavaScriptNode(2048);
            sourceJs.buffer = buffer;
            sourceJs.connect(context.destination);
            analyser = context.createAnalyser();
            analyser.smoothingTimeConstant = 0.6;
            analyser.fftSize = 512;
            
            source = context.createBufferSource();
            source.buffer = buffer;
            source.loop = true;
            
            source.connect(analyser);
            analyser.connect(sourceJs);
            source.connect(context.destination);

                       //////////////////////////////////// 
                       //////////VOLUME////////////////////                            
                       gainNode = context.createGain();                        
                       source.connect(gainNode);                         
                       gainNode.connect(context.destination);
                       //////////////////////////////////////
                        
            sourceJs.onaudioprocess = function(e) {
                array = new Uint8Array(analyser.frequencyBinCount);
                analyser.getByteFrequencyData(array);
                boost = 0;
                for (var i = 0; i < array.length; i++) {
                    boost += array[i];
                }
                boost = boost / array.length;
            };
            
            
            
            // popup
            //aca avisa cuando ya cargo el buffer
        },
        function(error) {
            $('#info').text('Decoding error:' + error);
        }
    );
};

Then I used this to turn off the volume but not working:

...gainNode.gain.value = 0;

Solution

  • You need the gain node to be the only thing that the output of source connects to.

    Right now, it has multiple connections and your gain node is only one of them - which means it's not affecting your whole signal.