Search code examples
jfugue

JFugue: Get music string duration


Given the music string Aq Aq Bi Bi Ci Ci is there an object in JFugue that can retrieve its duration (as a double or as a string)?

For example:

double musicStringDuration = new DurationMapper().getDoubleMSDuration("Aq Aq Bi Bi Ci Ci");
System.out.println(musicStringDuration); \\ prints 1.0

Solution

  • JFugue's org.jfugue.tools package contains several tools, including one that will tell you the total duration of a each voice (whether those voices is written as Staccato Strings like you have, or as MIDI channels for music you import, or anything else that JFugue can parse - and it's easy to write new parsers). ComputeDurationForEachTrackTool (and another tool, GetInstrumentsUsedTool) are ParserListeners, and there is a common pattern in JFugue to use a Parser Listener:

    *Some*Parser parser = new *Some*Parser();
    *Another*ParserListener listener = new *Another*ParserListener();
    parser.addParserListener(listener);
    parser.parse(*whatever the parser takes*);
    *Type* *value* = listener.*method*();
    

    Specifically for your case, you would have:

    StaccatoParser parser = new StaccatoParser();
    ComputeDurationForEachTrackTool tool = new ComputeDurationForEachTrackTool();
    parser.addParserListener(tool);
    parser.parse("Aq Aq Bi Bi Ci Ci");
    double[] durationsOfEachVoice = tool.getDurations();
    

    While this is longer than the statement you suggested in your question, this is immensely powerful, as it provides a means to connect any parser to any parser listener or tool.

    You would find 1.0 in durationsOfEachVoice[0].

    Actually, you'll find 2.0 in there, which is unexpected. But I just ran a test on it, and it's returning 0.5 for a quarter note and 0.25 for an eighth note. Sounds like a fix for JFugue version 6! In the meantime, please divide by 2.0 and accept my apologies.