【问题标题】:(Web Audio API) Oscillator node error: cannot call start more than once(Web Audio API) 振荡器节点错误:不能多次调用 start
【发布时间】:2015-11-16 16:02:31
【问题描述】:

当我启动振荡器时,停止它,然后再启动它;我收到以下错误:

Uncaught InvalidStateError: Failed to execute 'start' on 'OscillatorNode': cannot call start more than once.

显然我可以使用gain 来“停止”音频,但这让我觉得这是一种糟糕的做法。有什么更有效的方法可以在停止振荡器的同时重新启动它?

代码 (jsfiddle)

var ctx = new AudioContext();
var osc = ctx.createOscillator();

osc.frequency.value = 8000;

osc.connect(ctx.destination);

function startOsc(bool) {
    if(bool === undefined) bool = true;
    
    if(bool === true) {
        osc.start(ctx.currentTime);
    } else {
        osc.stop(ctx.currentTime);
    }
}

$(document).ready(function() {
    $("#start").click(function() {
       startOsc(); 
    });
    $("#stop").click(function() {
       startOsc(false); 
    });
});

当前解决方案(提问时):http://jsfiddle.net/xbqbzgt2/2/

最终解决方案:http://jsfiddle.net/xbqbzgt2/3/

【问题讨论】:

  • 它看起来像是实现的限制..您可以尝试在每个start()上创建一个新的OscillatorNode

标签: javascript web-audio-api javascript-oscillator


【解决方案1】:

更好的方法是启动一次振荡器节点,并在需要时将振荡器节点与图表连接/断开,即:

var ctx = new AudioContext();
var osc = ctx.createOscillator();   
osc.frequency.value = 8000;    
osc.start();    
$(document).ready(function() {
    $("#start").click(function() {
         osc.connect(ctx.destination);
    });
    $("#stop").click(function() {
         osc.disconnect(ctx.destination);
    });
});

muting the thermin(mozilla 网络音频 api 文档)中的静音方法

【讨论】:

【解决方案2】:

到目前为止,我发现的最佳解决方案是保持相同的 audioContext,同时在每次需要使用它时重新创建 oscillator

http://jsfiddle.net/xbqbzgt2/3/

仅供参考,每个浏览器页面生命周期(或至少每个我的硬件)只能创建 6 个 audioContext 对象:

Uncaught NotSupportedError: Failed to construct 'AudioContext': The number of hardware contexts provided (6) is greater than or equal to the maximum bound (6).

【讨论】:

  • “每个浏览器页面生命周期只能创建 6 个 audioContext 对象”。在我的情况下,这是 4,但谢谢,这非常有帮助并解决了我遇到的一个问题。
【解决方案3】:

据我所知,振荡器只能播放一次,原因与精度有关,而且还没有人很好地解释过。决定使用这种“只播放一次”模式的人可能会认为使用零音量设置在序列中间插入静音是一种很好的做法。毕竟,它确实是断开连接并重新创建方法的唯一替代方法。

【讨论】:

    猜你喜欢
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    相关资源
    最近更新 更多