AudioContext Oscillator won't play more than once

419 views Asked by At

I know that you can't play an oscillator more than once, so i wrote a function that creates a new one every time:

function playFrequency(f, t0, t1){
    console.log(f, t0, t1);
    var oscillator = self.audioContext.createOscillator();
    oscillator.type = "square";
    oscillator.frequency.value = f;
    oscillator.connect(self.audioContext.destination);
    oscillator.start(t0);
    oscillator.stop(t1);
}

But the strange thing is that the function will actually play the sound only once. I can't understand why this happens. Am I not creating a new oscillator every time I call the function?

When I create a function "playFrequency2(f, t0, t1)" which has the exact same code, it will play a sound even after the first function has played the sound. But it won't play the sound when I call it the second time too.

1

There are 1 answers

0
Julien Grégoire On BEST ANSWER

Your problem is with the start time your passing to your function. Start time is calculated from the audioContext currentTime which starts when the audioContext is created and keep moving forward from then on. So when you start your first sound at 0 for example and then end it at 3, your audioContext will keep running after that. So if you call your new sound with same time arguments, it won't play because your start time is before currentTime. You could modify like this:

function playFrequency(f, t1){
    console.log(f, t0, t1);
    var oscillator = self.audioContext.createOscillator();
    oscillator.type = "square";
    oscillator.frequency.value = f;
    oscillator.connect(self.audioContext.destination);
    oscillator.start();
    oscillator.stop(self.audioContext.currentTime+t1);
}