0

I am working on a music application, in Scala, to generate MIDI sequences in real time. The MIDI messages are being sent to another application (Ableton DAW) and possibly even external hardware. Accurate timing is very important for this use case, otherwise the resulting music will sound off-time.

I tried using java.util.Timer to schedule notes on different sequences but apparently that timer can drift by hundreds of milliseconds.

What is the most accurate Timer to use in Scala (or Java) is this even a reasonable task to try to accomplish on the JVM? or maybe I'm going about this all wrong?

jpyams
  • 4,030
  • 9
  • 41
  • 66
driangle
  • 11,601
  • 5
  • 47
  • 54
  • Isn't the actual MIDI composition handled with a downstream sequencer? Read this as: sending individual 'instructions' on a specific time sounds not-fun, while sending a stream with *logical timings* (and letting "something else", such as a native OS driver) deal with the to-hardware transformation is entirely feasible, but that doesn't require strict 'Timer' usage.. – user2864740 Aug 26 '18 at 02:09
  • 2
    I think you're right. What I'm currently sending is individual MIDI messages (ie: Note On, Note Off) and expecting my DAW to play them immediately. I probably need to rethink my approach. – driangle Aug 26 '18 at 02:15

1 Answers1

0

Usual timer implementations are based on the scheduler. If you need accuracy, you can roll your own:

def after(when: Duration)(f: => Unit) { 
  val deadline = when.fromNow
  while(! deadline.isOverdue) ()
  f
}

This will burn your cpu like crazy, but it doesn't get any more accurate than that.

Dima
  • 39,570
  • 6
  • 44
  • 70