2017-07-01 25 views
2

我正在研究一個項目,我正在嘗試使用音頻上下文生成音調。這是我到目前爲止:如何在兩個函數之間來回

$("#btn").click(function(){ 
    var context = new (window.AudioContext || window.webkitAudioContext)(); 
    var osc = context.createOscillator(); // instantiate an oscillator 
    osc.type = 'sine'; // this is the default - also square, sawtooth, triangle 
    osc.frequency.value = 440; // Hz 
    osc.connect(context.destination); // connect it to the destination 
    osc.start(); // start the oscillator 
    osc.stop(context.currentTime + 1); 
    }) 

我從stackoverflow得到的解決方案。它完美地使我尋找的基調。但是,它僅適用於少於六次激活。換句話說,當我點擊按鈕(帶有id ===「btn」)六次以上時,它就不再發出提示音了。

這裏是jsFiddle.net鏈接具有相同的語法如上click here

你能幫我解決這個問題?

+1

https://stackoverflow.com/questions/43511096/uncaught-domexception-failed-to -construct-audiocontext-the-number-of-hardwar和https://stackoverflow.com/questions/25046470/failed-to-construct-audiocontext-number-of-hardware-contexts-reached-maximum –

回答

1

您必須在osc.stop之後撥打context.close()。但這並不是微不足道的,因爲如果你在之後調用它,它甚至不會播放音頻,因爲它是異步的。

一個解決辦法是把它放在裏面setTimeout

// ... 
osc.start(); 
osc.stop(context.currentTime + 1); 
setTimeout(function() { 
    osc.close(); 
}, 1000); // 1000 = 1s used at .stop 

Alterantively,你可以做兩個.stop。和.closesetTimeout

// ... 
osc.start(); 
setTimeout(function() { 
    osc.stop(); // note that there is no when argument, i.e. stop immetidately 
    osc.close(); 
}, 1000); 

在我看來,第二個選項是更好,因爲你沒有匹配停止和暫停時間。


從問題的代碼示例,最佳答案更新:

$("#one").click(function(){ 
 
    var context = new (window.AudioContext || window.webkitAudioContext)(); 
 
    var osc = context.createOscillator(); // instantiate an oscillator 
 
    osc.type = 'sine'; // this is the default - also square, sawtooth, triangle 
 
    osc.frequency.value = 440; // Hz 
 
    osc.connect(context.destination); // connect it to the destination 
 
    osc.start(); // start the oscillator 
 
    setTimeout(function() { 
 
    osc.stop(); 
 
    context.close(); 
 
    }, 1000); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="search"> 
 
<button id="one"> 
 
hello 
 
</button>

相關問題