Devan Somaia
Devan Somaia

Reputation: 645

How to Convert TimeStamps to Ticks (PPQ) - Real Time Midi

I'm currently reading in MIDI messages in real-time from my midi keyboard using a class that implements Receiver, and outputting the notes played.

The only information i receive when I press a note is the MidiMessage and a timeStamp.

I am trying to paint the notes as actual piano sheet music and currently the user has to set the bpm beforehand.

Therefore if I know the tempo is 120bpm (for example), how can I use the timeStamps to determine the length of the note pressed?

I'm assuming if I can convert the timeStamps into ticks (ppq), then I can use that to work out the timings.

Any help is greatly appreciated. Below is my "send" method in my Receiver class.

The 'firstStamp' and 'secondStamp' variables are just to output the length of a note. I took the timeStamp when a note was released and subtracted the timeStamp when it was pressed.

@Override
public void send(MidiMessage message, long timeStamp) {

    String  strMessage = null;

    if (firstStamp == 0) {
        firstStamp = timeStamp;
        secondStamp = timeStamp;
    }

    firstStamp = secondStamp;
    secondStamp = timeStamp;

    stampDif = (secondStamp - firstStamp);

    if (message instanceof ShortMessage) {

        strMessage = decodeMessage((ShortMessage) message, timeStamp);


    } else if (message instanceof MetaMessage) {

        strMessage = decodeMessage((MetaMessage) message);

    } else if (message instanceof SysexMessage) {

        strMessage = decodeMessage((SysexMessage) message);

    } else {
        strMessage = "other message" + message.getStatus();
    }
    r_out.println("Timestamp: " + timeStamp + " " + strMessage);
    r_printStream.println("Timestamp: " + timeStamp + " " + strMessage);

}

Upvotes: 1

Views: 2369

Answers (1)

Roger Lindsjö
Roger Lindsjö

Reputation: 11543

If the timestamp is in milliseconds then you can convert it to ticks like this:

long ticks = timestamp * bpm / (1000 * 60); 

Bit you will get a high start tick since the timestamp is probably since Jan 1 1970. So if you want to have your first "tick" as 0 you need to keep track of if this is your first seen event.

if (tickOffset == -1) { // Using -1 as not initialized
    tickOffset = ticks;
}
ticks = ticks - tickOffset;

Upvotes: 2

Related Questions