Reputation: 915
I want to sound an oscillator note for 2 seconds. But the next time, even after recreating a new oscillator, no sound is played:
oscillator = context.createOscillator();
oscillator.frequency.value = 440;
oscillator.type = oscillator.SINE;
oscillator.connect(context.destination);
oscillator.start(0);
oscillator.stop(2);
If I omit stop(2) and instead use setTimeout() to oscillator.stop() in a function, it works. I have read that the node should be disconnected, but disconnect() does not accept a time as argument, only an output index. Any pointer for the solution?
Upvotes: 1
Views: 229
Reputation: 13908
The "when" parameter to start and stop is based on AudioContext.currentTime. Zero means "now" - currentTime also starts at zero when the AudioContext is created. So when you say ".start(0); .stop(2);" the second time around, the "stop" is already in the past (check AudioContext.currentTime - it's already >2), so the start never causes any effect.
Instead of what you're currently doing, do:
oscillator.start(context.currentTime);
oscillator.stop(context.currentTime+2);
Upvotes: 2