2014-04-23 71 views
3

我很好奇我怎麼能在web音頻api中做一個叫做「扼流器」的東西。當我用鍵播放聲音時,如果再次按下該鍵,我希望它停止聲音並再次播放。任何想法如何做到這一點?如何使用網絡音頻api重新觸發(阻塞)聲音

我迄今爲止代碼:

$(document).on("keydown", function(e) { 
console.log(e); 
switch (e.keyCode) { 
    case 81: // Q 
     playKick(BUFFERS.kick); 
    break; 
} 
}) 

function playKick(instrument) { 
    source1 = context.createBufferSource(); 
    source1.buffer = instrument; 
    source1.loop = true; 
    source1.connect(context.destination); 
    if (!source1.start) 
     source1.start = source1.noteOn; 
    source1.start(0); 
    } 

回答

2

你要保持到當前播放的聲音的參考。因此需要在playKick範圍之外提供。然後,在playKick之內,在創建新聲音並將其分配給該全局變量之前,請在舊聲音上調用stopnoteOff

喜歡的東西:

var current; 

$(document).on('keydown', function(e) { 
    console.log(e); 
    switch (e.keyCode) { 
    case 81: 
     playKick(BUFFERS.kick); 
    break; 
    } 
}); 

function playKick(instrument) { 
    var source = context.createBufferSource(); 
    source.buffer = instrument; 
    source.loop = true; 
    source.connect(context.destination); 
    if (current) { 
    if (!current.stop) { 
     current.stop = current.noteOff; 
    } 
    current.stop(0); 
    } 
    if (!source.start) { 
    source.start = source.noteOn; 
    } 
    source.start(0); 
    current = source; 
} 

當然,一定會有更好的方式來組織這一點 - 但希望這將讓你開始。