【问题标题】:AudioContext gain Node does not mute audio source (Web Audio API)AudioContext 增益节点不静音音频源(Web Audio API)
【发布时间】:2017-12-15 00:30:41
【问题描述】:

我使用 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;
}

关于我是否错误地设置了增益节点有什么想法吗?有没有更好的静音方法?

谢谢!

【问题讨论】:

    标签: javascript web-audio-api


    【解决方案1】:

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

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

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

    this.gainNode.gain.value = 0;
    

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

    【讨论】:

    • 除此之外,请查看 Firefox 中的调试工具,它可以直观地显示图表,从而很容易发现此类问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 2012-08-28
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多