Web Audio API Oscillator Node object lifetime and stop () method

I am trying to understand web audio API methods and scheduling methods.

But I still do not understand the Oscillator Node stop() method completely.

Here I am trying to adjust the playback of 4 oscillators with a tempo of 120 BPM.

But it seems that as soon as the stop() method starts the release time, it stops all generators.

Here is the code:

 var context = new webkitAudioContext(); var now = context.currentTime; var tempo = 120; var releaseTime = 0.5; var secondsPerBeat = 60.0 / tempo; for(var i = 0; i < 4; i++){ var now = context.currentTime; var osc = context.createOscillator(); osc.connect(context.destination); osc.start(now + (i*secondsPerBeat)); var now = context.currentTime; osc.stop(now + releaseTime); } 

Why is this happening and how can I prevent it?

thanks

+4
source share
2 answers

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).

+2
source

I had problems with something similar to this. I found that you need to stop() AND ALSO disconnect() each generator (or another buffer creating a node type), or instances will be delayed and will interfere with the playback of any new instances.

+1
source

Source: https://habr.com/ru/post/1491077/


All Articles