2015-06-01 135 views
1

我一直在尋找Web Audio API,並且無法獲得音頻增益。我在這裏設置了一個小提琴,所以你可以理解這個功能的應用:http://jsfiddle.net/mnu70gy3/Web Audio Api,設置增益

我希望能夠在點擊事件中動態創建一個音色,但是不能讓那個音色淡出。下面是相關的代碼:

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); 
} 

任何想法,如果這可以做?

+0

你見過[這](http://jsfiddle.net/JCTJj/19/)?還包括關於如何使用滑塊進行調整的代碼(以及已發表的評論)。 – lalengua

回答

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

的你需要斷開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);