(Web Audio API) Oscillator node error: cannot call start more than once

我的未来我决定 提交于 2019-12-30 03:50:29

问题


When I start my oscillator, stop it, and then start it again; I get the following error:

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

Obviously I could use gain to "stop" the audio but that strikes me as poor practice. What's a more efficient way of stopping the oscillator while being able to start it again?

code (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); 
    });
});

Current solution (at time of question): http://jsfiddle.net/xbqbzgt2/2/

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


回答1:


A better way would be to start the oscillatorNode once and connect/disconnect the oscillatorNode from the graph when needed, ie :

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);
    });
});

This how muting in done in muting the thermin (mozilla web audio api documentation)




回答2:


The best solution I've found so far is to keep the SAME audioContext while recreating the oscillator every time you need to use it.

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

FYI You can only create 6 audioContext objects per browser page lifespan (or at least per my hardware):

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



回答3:


From what I know, an oscillator can only be played once, for reasons having to do with precision, and never well explained by anyone yet. Whoever decided on this "play only once" model probably would consider it good practice to use a zero-volume setting to insert silence in the middle of a sequence. After all, it really is the only alternative to the disconnect-and-recreate method.



来源:https://stackoverflow.com/questions/32161832/web-audio-api-oscillator-node-error-cannot-call-start-more-than-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!