AudioContext: Oscillator - know when all sounds have been played

218 views Asked by At

I am using this javascript api (miniMusic). I was able to create a music and then export the javascript code. I am also able to run it.

I would like to be able to know when my music has ended so I can play it again and have control over it.

with(new AudioContext)
for(i in D=[12,,,13,,,18,,,,,,12,,,13,,,18,,,,,,12,,,13,,,18,,,15,,,12,,,8,,,12,,,13]) {
   with(createOscillator())
   if(D[i]) {
      connect(destination) 
      frequency.value=800*1.06**(13-D[i]),
      type='square',
      start(i*.1),
      stop(i*.1+.1)
   }
}
// -> onEnd = function (...) {}

The loop runs instantly so I can't use indexes to locate in what note the music is playing at. Can someone help me?

1

There are 1 answers

0
Alessi 42 On BEST ANSWER

Oscillator has an onend function which is called when the tone ends, however the api you linked creates a new oscillator for each note, you could count the number of notes played and then loop once the number of notes is equal to the number of notes in the tune.

Example

with(new AudioContext)
for (i in D = [12, , , 13, , , 18, , , , , , 12, , , 13, , , 18, , , , , , 12, , , 13, , , 18, , , 15, , , 12, , , 8, , , 12, , , 13]) {
  with(createOscillator())
  if (D[i]) {
    onended = function() {
      console.log('Note has stopped playing');
    }
    connect(destination)
    frequency.value = 800 * 1.06 ** (13 - D[i]),
      type = 'square',
      start(i * .1),
      stop(i * .1 + .1)
  }
}

Hope this helps!