Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 225
Peter Varo Avatar asked Mar 17 '23 17:03

Peter Varo


1 Answers

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

like image 174
Alnitak Avatar answered Mar 19 '23 06:03

Alnitak