Web Audio Api,设置增益

时间:2015-06-01 01:02:00

标签: javascript web-audio

我一直在关注Web Audio API,但无法获得音频增益。我在这里设置了一个小提琴,因此您可以理解该功能的应用:http://jsfiddle.net/mnu70gy3/

我希望能够在点击事件中动态创建一个音调,但是我无法淡出这种音调。以下是相关代码:

var audioCtx = new AudioContext();
var osc = {};  // set up an object for all the oscillators
var gainNodes = {};  // set up an object for all the gains
var now;
function tone(id,freq) {

    // create osc / set gain / connect osc
    gainNodes.id = audioCtx.createGain();
    osc.id = audioCtx.createOscillator();
    osc.id.connect(audioCtx.destination);

    // set frequency
    osc.id.frequency.value = freq;

    // set gain at 1 and fade to 0 in one second
    gainNodes.id.gain.value = 1.0;
    gainNodes.id.gain.setValueAtTime(0, audioCtx.currentTime + 1);

    // start and connect
    osc.id.start(0);
    osc.id.connect(audioCtx.destination); 
}

是否可以这样做?

2 个答案:

答案 0 :(得分:2)

在您的代码中,您将振荡器连接到destination两次。 而不是连接oscillator -> gain -> destination

gainNodes.id = audioCtx.createGain();
osc.id = audioCtx.createOscillator();
osc.id.connect(gainNodes.id);

// set frequency and gain
osc.id.frequency.value = freq;
gainNodes.id.gain.value = 1.0;
gainNodes.id.gain.setValueAtTime(0, audioCtx.currentTime + 1);

// start and connect
osc.id.start(0);
gainNodes.id.connect(audioCtx.destination);

答案 1 :(得分:1)

再次单击磁贴时,需要断开audioCtx.destination。

https://jsfiddle.net/2dyq2ajw/

function dismissTone(id,freq) {
    gainNodes.id.gain.value = 0; 
    osc.id.disconnect(audioCtx.destination);
}

    if($(this).hasClass('xx'))
        tone(thisId,thisFreq);
    else
        dismissTone(thisId,thisFreq);