Jump to content

Make update loop in sync with music and notes in Phaser


Kai23
 Share

Recommended Posts

Hi erveryone !

I'm trying to make some notes appearing when the music hits a certain time in Phaser, but when I log the "hit times" in the console, it only show up sometimes.

I have an object of "notes", the key being the time I expect the note to show :

{
  1371: {
    jam: 1,
    duration: 0.40
  }
}

But, in the update loop, if I do something like this :

update () {
  if (music && music.currentTime) {
    if (notes[music.currentTime]) {
      console.log('notes[music.currentTime].jam', notes[music.currentTime].jam)
    }
  }
}

It logs only some of the notes, randomly.

 

Even something like this : 

if (music && music.currentTime) {
  var time = Math.floor(music.currentTime)
  if (time === 1371) {
    console.log('time', time)
  }
}

 never trigger the log

 

Do you have any idea why ?

Link to comment
Share on other sites

finally, the solution was to do something like this : 

var notes = [    
    ...
    {'start': 1377, 'jam': 1, 'duration': 0.40},
    {'start': 2456, 'jam': 1, 'duration': 0.30},
    ...
];

// Index of the first note that will be played.
// Will be incremented by 1 or more with some update() calls,
// depending on the time that passed.
var nextNote = 0;

function update() {
    // Process all notes that are now in the past
    // compared to the current time of the playing music,
    // but skip notes that have been already played before.
    while (music && nextNote < notes.length && notes[nextNote].start <= music.currentTime) {
        console.log(notes[nextNote]);
        nextNote += 1;
    }
}

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...