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

时间:2017-12-13 18:07:45

标签: 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;
}

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

谢谢!

1 个答案:

答案 0 :(得分:4)

问题是你仍然将bufferource直接连接到目的地并通过增益节点连接它 - 所以你有效地从源缓冲区到目的地有一条补丁电缆(一条通过增益节点)。您应该删除以下行:

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

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

this.gainNode.gain.value = 0;

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