I'm trying to code a rhythm game in Java. I'm playing an audio file with a javax.sound.sampled.Clip
and I want to know the exact position where I am.
Following my researches, a good practice for a rhythm game is to keep track of the time using the position in the music playing instead of the System time (to avoid a shift between the audio and the game).
I already coded a main loop which uses System.nanoTime()
to keep a consistent frame rate. But when I try to get the time of the clip, I have the same time returned for several frames. Here is an extract from my code :
while (running) {
// Get a consistent frame rate
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
timer += now - lastTime;
lastTime = now;
if (delta >= 1) {
if(!paused) {
tick((long) Math.floor(delta * timePerTick / 1000000));
}
display.render();
ticks++;
delta--;
}
// Show FPS ...
}
// ...
private void tick(long frameTime) {
// Doing some stuff ...
System.out.println(clip.getMicrosecondPosition());
}
I was expecting a consistent output (with increments of approximately 8,333 µs per frame for 120 fps) but I get the same time for several frames.
Console return:
0
0
748
748
748
10748
10748
10748
20748
20748
20748
30748
How can I keep consistently and accurately keep track of the position where I am in the song ? Is there any alternative to the javax Clip ?