2017-07-01 9 views
2

私は現在、オーディオコンテキストを使用してトーンを生成しようとしているプロジェクトに取り組んでいます。ここに私がこれまでに来たものです: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); 
    }) 

私は解決策を得ました。それは完璧に私が探しているトーンを作る。ただし、6回以下のアクティベーションでのみ動作します。言い換えれば、ボタンを6回以上(id === "btn"で)クリックすると、もはやトーンを作りません。ここで

click here

上記と同じ構文を持つjsFiddle.netリンクはあなたは私が問題を解決する手助けすることはできますか?

+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を行うことができます。そしてsetTimeout内部.close:私の意見では

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

、2番目のオプションは、あなたが停止し、タイムアウト時間を一致させる必要はありませんので、良いです。


質問、答えを更新からのコード例:

$("#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>

関連する問題