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.
Your problem is with the
start
time your passing to your function. Start time is calculated from theaudioContext
currentTime
which starts when theaudioContext
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, youraudioContext
will keep running after that. So if you call your new sound with same time arguments, it won't play because yourstart
time is beforecurrentTime
. You could modify like this: