EmilyJ
EmilyJ

Reputation: 892

Web Audio API Stop after delay

I have this snippet to play a tone. I set the delay in the stop() function to 5 sec. It works the first time it is called. But any subsequent called the delay did not occur - it just stops as soon as the time1 expired.

Any suggestions what is the problem?

function playSound() {
    var mySource = myAudioContext.createOscillator();
    var myGain = myAudioContext.createGainNode();

    mySource.frequency.value = 261.625;
    mySource.connect(myGain);
    myGain.gain.value = 1.0;
    myGain.connect(myAudioContext.destination);

    mySource.start(0);
    setTimeout(function(s) {
               mySource.stop(5);   //stop after 5 sec. only works for the first call
               }, time1, mySource);

}

Upvotes: 0

Views: 256

Answers (1)

cwilso
cwilso

Reputation: 13908

stop(n) does not take effect "after n seconds from now." It's an absolute time - and time starts at zero, so the first time it appears to work[*].

Use this instead:

mySource.stop( 5 + myAudioContext.currentTime );

[*] This actually also relies on a bug in Webkit/Blink right now, where we don't start time running until the first node is created; it's supposed to start when the AudioContext is created.

Upvotes: 3

Related Questions