javascript - Web Audio API - 停止连接到释放包络的振荡器的正确方法

标签 javascript web-audio-api envelope web-midi

我正在使用 WebAudioAPIWebMIDIAPI 创建一个复音合成器。我的两个振荡器中的每一个都有一个增益节点,然后连接到一个主增益节点。

我想知道如何在释放后正确停止(并在必要时删除?)振荡器。我不确定是否有必要调用 oscillator.stop() 并从数组中删除振荡器。

如果我这样做,释放包络不起作用,音符会立即停止;如果我不这样做,释放包络会起作用,但音符有时可以永远播放下去。

编辑:似乎当 .stop() 功能未实现并且同时演奏两个音符时,其中一个振荡器将始终保持打开状态。不确定是我的代码还是??

我的 noteOff 函数代码如下:

/**
 * Note is being released
 */
this.noteOff = function (frequency, velocity, note){

    var now = this.context.currentTime;

    // Get the release values
    var osc1ReleaseVal = now + this.osc1Release;
    var osc2ReleaseVal = now + this.osc2Release;

    // Cancel scheduled values
    this.oscGain.gain.cancelScheduledValues(now);
    this.osc2Gain.gain.cancelScheduledValues(now);

    // Set the value
    this.oscGain.gain.setValueAtTime(this.oscGain.gain.value, now);
    this.osc2Gain.gain.setValueAtTime(this.osc2Gain.gain.value, now);

    // Release the note
    this.oscGain.gain.linearRampToValueAtTime(0.0, osc1ReleaseVal);
    this.osc2Gain.gain.linearRampToValueAtTime(0.0, osc2ReleaseVal);

    // ----- IF I COMMENT THE `forEach` Loop the release works correctly but with side-effects!
    // Stop the oscillators
    this.oscillators[frequency].forEach(function (oscillator) {
        oscillator.stop(now);
        oscillator.disconnect();
        delete oscillator;
    });
};

非常感谢任何帮助,谢谢!

最佳答案

不要使用 oscillator.stop(now)。使用 oscillator.stop(osc1ReleaseVal) 安排振荡器在增益变为 0 的同时停止。

您不必断开连接并删除振荡器。一旦停止,振荡器可以自行断开与增益节点的连接。如果您删除对振荡器的引用,它可能会被垃圾回收。

关于javascript - Web Audio API - 停止连接到释放包络的振荡器的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43610937/

相关文章:

matlab - 归一化两个音频信号的能量

c# - 使用信封重载 xml 中的命名空间

javascript - 使用 Google map API 自动完成地址

JavaScript regex(正则表达式)

javascript - 如何在不使用 Web Audio API 的情况下直接从 ArrayBuffer 获取 channel 数据?

javascript - 在Web Audio API中通过PeriodicWave播放缓冲区,我可以将增益设置为与缓冲区一样大吗?

java - 如何通过xml签名文件提取 "original"内容

Javascript:快速查找对象中的值(就像我们可以使用属性一样)

javascript - 从 ng-repeat 中删除元素,但将其 HTML 保留在 dom 中

html - html5音频和WebAudio是BFF-是吗?