Firstly, about Javascript: in Js there is no block area, so perhaps it will be clearer to put all the definitions of vars at the beginning of the current execution context.
Secondly, you start your sound with a delay, but stop them at the same time that you are not looking. Thirdly, currentTime will be pretty much the same in a for loop: you cannot rely on a for loop to cause a delay.
var context = new webkitAudioContext(); var tempo = 120; var releaseTime = 0.5; var secondsPerBeat = 60.0 / tempo; var now = context.currentTime; var i = 0, startTime=0, osc = null; for(i = 0; i < 4; i++) { startTime = now + (i*secondsPerBeat) ; osc = context.createOscillator(); osc.connect(context.destination); osc.start(); osc.stop(startTime + releaseTime); }
Soon enough, you will want to write a function to create your own oscillator to further eliminate the code.
Edit: about the life of your objects, it is best to look at the specifications:
https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
see 4.2.3. Life part.
to summarize: if you play or are connected to a reference context, they will survive and die differently.
You can:
- maintain the same context and store 4 oscillators in the array, to simply start / stop them after necessary.
- or each time create a new context + new oscillators.
(but you cannot continue to create new oscillators in the same context or they accumulate because they are still connected and use too much memory).
source share