如何在两个功能之间来回切换

时间:2017-07-01 16:28:49

标签: javascript jquery html css

我正在开发一个项目,我正在尝试使用音频上下文生成音调。这是我到目前为止所得到的:

Ctrl + .

我从stackoverflow获得了解决方案。它完美地使我正在寻找的基调。但是,它仅适用于少于六次激活。换句话说,当我点击按钮(id ===“btn”)超过六次时,它就不再发出声音了。

这是jsFiddle.net链接,其语法与上面的click here

相同

你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您必须在context.close()之后致电osc.stop。但这并非如此微不足道,因为如果你之后立即调用它,它甚至不会播放音频,因为它是异步的。

解决方案是将其置于setTimeout

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

Alterantive,你可以同时做.stop。和.close内的setTimeout

// ...
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>

相关问题