AudioContext 增益节点不会使音频源静音(Web Audio API)

Sur*_*urz 3 javascript web-audio-api

我使用three.js和Web Audio API制作了一些音乐可视化,但在静音音频时遇到了问题。

我目前有一个带有分析器和源缓冲区的 AudioContext 对象。我正在添加一个增益节点来使音频静音,目前该节点无法正常工作。当我单击静音时,音频电平会发生变化(实际上变大了),所以我知道增益正在影响某些东西。

代码:

// AudioHelper class constructor

function AudioHelper() {
    this.javascriptNode;
    this.audioContext;
    this.sourceBuffer;
    this.analyser;
    this.gainNode;
    this.isMuted;
}

// Initialize context, analyzer etc

AudioHelper.prototype.setupAudioProcessing = function () {
    // Get audio context
    this.audioContext = new AudioContext();

    this.isMuted = false;

    // Create JS node
    this.javascriptNode = this.audioContext.createScriptProcessor(2048, 1, 1);
    this.javascriptNode.connect(this.audioContext.destination);

    // Create Source buffer
    this.sourceBuffer = this.audioContext.createBufferSource();

    // Create analyser node
    this.analyser = this.audioContext.createAnalyser();
    this.analyser.smoothingTimeConstant = 0.3;
    this.analyser.fftSize = 512;

    this.gainNode = this.audioContext.createGain();

    this.sourceBuffer.connect(this.analyser);
    this.analyser.connect(this.javascriptNode);
    this.sourceBuffer.connect(this.audioContext.destination);

    this.sourceBuffer.connect(this.gainNode);
    this.gainNode.connect(this.audioContext.destination);

    this.gainNode.gain.value = 0;
};


// This starts my audio processing (all this and the analyzer works)

AudioHelper.prototype.start = function (buffer) {
    this.audioContext.decodeAudioData(buffer, decodeAudioDataSuccess, decodeAudioDataFailed);
    var that = this;

    function decodeAudioDataSuccess(decodedBuffer) {
        that.sourceBuffer.buffer = decodedBuffer
        that.sourceBuffer.start(0);
    }

    function decodeAudioDataFailed() {
        debugger
    }
};

// Muting function (what isn't working)
AudioHelper.prototype.toggleSound = function() {
    if(!this.isMuted) {
        this.gainNode.gain.value = 0;
    } else {
        this.gainNode.gain.value = 1;
    }
    this.isMuted = !this.isMuted;
}
Run Code Online (Sandbox Code Playgroud)

关于我是否错误地设置增益节点的任何想法?有没有更好的方法来静音?

谢谢!

cwi*_*lso 6

问题是您仍然将缓冲区源直接连接到目标,并通过增益节点将其连接 - 因此您实际上有两根从源缓冲区到目标的跳线(一根通过增益节点)。您应该删除以下行:

this.sourceBuffer.connect(this.audioContext.destination);
Run Code Online (Sandbox Code Playgroud)

以及这一行(因为您希望它开始时不静音):

this.gainNode.gain.value = 0;
Run Code Online (Sandbox Code Playgroud)

我认为你会得到你期望的行为。