如何使用 setTargetAtTime 安排淡出

How do you schedule a fade-out using setTargetAtTime

我在使用 Web 音频 API 时遇到了所谓的 'windowing' 声音音高变化颗粒的问题。当我播放声音时,我使用 setValueAtTime 成功地将初始增益设置为 0,并使用 linearRampToValueAtTime 成功地淡化了声音。但是,我未能成功安排在声音结束前稍稍发生淡出。可能是因为声音发生了音高偏移,尽管在下面的代码中,我相信我已经正确设置了参数。尽管 setTargetAtTime 中的最后一个参数可能不合适,因为我不完全理解该参数,尽管已经阅读了 Chris 对此事的评论。如何使用 setTargetAtTime 在声音发生音高偏移时成功安排淡出?下面是我的代码。您可以在 https://vispo.com/animisms/enigman2/2022

查看该作品本身
            source.buffer = audioBuffer;
            source.connect(this.GrainObjectGain);
            this.GrainObjectGain.connect(app.mainGain);
            source.addEventListener('ended', this.soundEnded);
            //------------------------------------------------------------------------
            // Now we do the 'windowing', ie, when we play it, we fade it in,
            // and we set it to fade out at the end of play. The fade duration
            // in seconds is a maximum of 10 milliseconds and 
            // a minimum of 10% of the duration of the sound. This helps 
            // eliminate pops.
            source.playbackRate.value = this.playbackRate;
            var fadeDurationInSeconds = Math.min(0.01,0.1*duration*this.playbackRate);
            this.GrainObjectGain.gain.setValueAtTime(0, app.audioContext.currentTime);
            this.GrainObjectGain.gain.linearRampToValueAtTime(app.constantGrainGain, app.audioContext.currentTime+fadeDurationInSeconds);
            this.GrainObjectGain.gain.setTargetAtTime(0, app.audioContext.currentTime+duration*this.playbackRate-fadeDurationInSeconds, fadeDurationInSeconds);
            source.start(when, offset, duration);

根据您在下面的评论,我猜您想在声音结束前安排淡出 fadeDurationInSeconds

由于您更改了 playbackRate,您需要将原始 duration 除以那个 playbackRate 以获得实际持续时间。

按如下方式更改您的 setTargetAtTime() 呼叫应该安排在所需时间点淡出。

this.GrainObjectGain.gain.setTargetAtTime(
    0,
    app.audioContext.currentTime + duration / this.playbackRate - fadeDurationInSeconds,
    fadeDurationInSeconds
);

请注意 setTargetAtTime() 实际上从未达到 target。至少在理论上。尽管过了一段时间,它还是相当接近了。但是那个时间比 timeConstant.

规范中的相关文本可在此处找到:https://webaudio.github.io/web-audio-api/#dom-audioparam-settargetattime

Start exponentially approaching the target value at the given time with a rate having the given time constant. Among other uses, this is useful for implementing the "decay" and "release" portions of an ADSR envelope. Please note that the parameter value does not immediately change to the target value at the given time, but instead gradually changes to the target value.

timeConstant 参数粗略定义了达到所需信号衰减的 2/3 所需的时间。

这里提到了:https://webaudio.github.io/web-audio-api/#dom-audioparam-settargetattime-timeconstant

More precisely, timeConstant is the time it takes a first-order linear continuous time-invariant system to reach the value 1−1/ (around 63.2%) given a step input response (transition from 0 to 1 value).