【问题标题】:How to go back and forth between two functions如何在两个函数之间来回切换
【发布时间】:2017-07-02 00:45:59
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

您必须在osc.stop 之后调用context.close()。但这并不是那么简单,因为如果你在之后调用它,它甚至不会播放音频,因为它是异步的。

解决方案是将其放入setTimeout:

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

或者,您可以同时使用.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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多