0

I have a midi editor app in Java swing that can play back the loaded music. The resolution (ticks per quarter note value) can vary from 24 to 1000, with most midi files being in the higher range. I implemented a feature where the user can set the playback tempo in quarter beats per minute. The program varies the speed of the playback by calculating the Swing timer delay using

enter image description here

where BPM and resolution are the variables. Basically, the function just looks like y = 1/x, fixing a value for BPM. However, the Swing timer delay is an int value in milliseconds. For higher resolutions, the delay always rounds to 1 regardless of the BPM due to the nature of the function.

What is the best solution so that I can play back the music at a roughly accurate speed? Would I need to just use a faster timer? If so, what are the options? Should I write some logic that moves forward x midi ticks every timer tick instead of 1 to work around the Swing timer's limitations?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
ShokoN
  • 101
  • 1
  • 1

1 Answers1

1

Rounding errors will add up. And delays due to execution of your code will add up.

Therefore:

  • compute timestamps as floating-point values (so that individual timestamps might be off by ± 0.5 ms, but that the sum of time intervals is no worse); and
  • compute the absolute time of each event, and set the timer so that it elapses in target_time - current_time milliseconds, whatever that may be.
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
CL.
  • 173,858
  • 17
  • 217
  • 259