hacke
hacke

Reputation: 299

MIDI beat clock in Java

I'm creating a drum machine and I'm having some problems with outputting MIDI beat clock. For simplicity, I've set the internal clock to run by calling Thread.sleep(_time), where _time is the amount of time for a sixteenth note calculated by the following code:

/**
 * Calculates the length of a semiquaver in the sequencer
 * @return the time of a semiquaver in milliseconds
 */
private void calculateTempo()
{
    Log.i(DEBUG_TAG , "Calculated tempo.");

    /**
     * Fjärdedelsnot
     */
    _quarterNote = 60000/_tempo;

    /**
     * Sextondel
     */
    _sixteenthNote = (_quarterNote/4);


}

_tempo is an integer value for the BPM. As I said, my drum machine runs fine, but when outputting beat clock I'm running into problems. The beat clock in the slaved device expects to recieve 24 pulses per quarter note, which gives us a rate of 6 pulses per sixteenth note. I'm using a timer.scheduleAtFixedRate for adding messages to the output queue.

Say we have a tempo of 120 BPM, this gives us a time of 60000/120 = 500 per quarter note, which is 125 milli seconds for every sixteenth note. Every sixteenth note should have six pulses, 125 / 6 = 20.83333.. You can see why this puts me in a bit of a pickle. The scheduleAtFixedRate only takes milli seconds as a parameter, so I must make a counter with higher precision, but even if I use nanoseconds things will start to drift after a while..

I've really been combing through the Java MIDI api trying to find something that'll help me in this but I can't seem to find any methods designed for this. If you have any suggestions please do tell.

Cheers. /M

Upvotes: 3

Views: 830

Answers (1)

dariosalvi
dariosalvi

Reputation: 23

According to this link you can use Object.wait(millis, nanos) and Thread.sleep(millis, nanos) available from Java 5. If you want to schedule threads it suggests using the ScheduledThreadPoolExecutor.

I have also found this library, maybe it is worth a check.

Good luck!

Upvotes: 1

Related Questions