Search code examples
javascriptaudioweb-audio-api

Sound fades out, but does not fade in -- why?


I think I understand the main concept of Web Audio API, as well as how sounds are working in general. And even though I managed to make the sound "fade out", I cannot figure out, why it is not "fading in" in the following snippet I wrote to represent the problem:

(function ()
{
    'use strict';
    var context = new AudioContext(),
        wave = context.createOscillator(),
        gain = context.createGain(),
        ZERO = 0.000001;

    wave.connect(gain);
    gain.connect(context.destination);

    wave.type = 'sine';
    wave.frequency.value = 200;
    gain.gain.value = ZERO;

    wave.start(context.currentTime);

    gain.gain.exponentialRampToValueAtTime(1.00, 1.0);
    gain.gain.exponentialRampToValueAtTime(ZERO, 3.0);
})();

NOTE: The same problem appeared on Firefox (Linux) and Chrome (Windows) too


Solution

  • Replacing your gain.gain.value = ZERO line with:

    gain.gain.setValueAtTime(ZERO, 0);
    

    will fix the problem.

    The rationale is in the actual specification of the exponentialRampToValueAtTime() function:

    Schedules an exponential continuous change in parameter value from the previous scheduled parameter value to the given value

    So, if there's no previous scheduled parameter value (only a fixed value) then the function cannot interpolate. The same applies to the linearRampToValueAtTime function.

    This may also be useful from the MDN documentation:

    AudioParam.value ... Though it can be set, any modifications happening while there are automation events scheduled — that is events scheduled using the methods of the AudioParam — are ignored, without raising any exception