Kai23

Make update loop in sync with music and notes in Phaser

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 ?

Share this post


Link to post
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;
    }
}

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.