Skip to content
Advertisement

How could one draw sheet music from MusicXML in Java?

I am currently working on a sight-reading app that requires display of musical notation; I am struggling to find a way to efficiently draw this in a JFrame.

I am looking at the JFugue library to help with this, and the description of the class MusicXMLParser_J states the following.

Parses a MusicXML file, and fires events for ParserListener interfaces when tokens are interpreted. The ParserListener does intelligent things with the resulting events, such as create music, draw sheet music, or transform the data. MusicXmlParser.parse can be called with a file name, File, InputStream, or Reader.

However, I am not certain which class that implements ParserListener would allow the drawing of sheet music. Any help is greatly appreciated.

Advertisement

Answer

JFugue does not come with a ParserListener that draws sheet music, but you can write your own! Plus, when you write a ParserListener, it will work for any parser, so you would also have the ability to draw sheet music for MIDI files and other file types that people have Parsers for. If you make a lot of progress on this, please consider submitting it for the next version of JFugue.

Here is one way to write your own sheet music parser listener:

public class ArunavSheetMusicParserListener extends JPanel implements ParserListener {
    private List<ThingToDraw> thingsToDraw;

    public ArunavSheetMusicParserListener() { 
        super();
        this.thingsToDraw = new ArrayList<>();
    }

    @Override
    public void paint(Graphics g) {
        super(g);
        for (ThingToDraw thingToDraw : thingsToDraw) {
            thingToDraw.draw(g);
        }
    }

    @Override
    public void onNoteParsed(Note note) {
        thingsToDraw.add(new NoteDrawing(note));
    }

    ...and so on for the other events from ParserListener that you wish to draw...
}

and

public interface ThingToDraw {
    public void draw(Graphics g);
}

and

public class NoteDrawing implements ThingToDraw {
    private Note note;

    public NoteDrawing(Note note) {
        this.note = note;
    }

    public void draw(Graphics g) {
        // look at the methods of the note to determine
        // how to draw it:
        //   - note.getDuration()
        //   - note.getValue()
    }
}

and do this for other things you plan to draw.

Please note: MusicXMLParser is contributed by the user community, and is not as well maintained as other parts of the JFugue library. Before investing time in your own ParserListener, make sure the MusicXMLParser is working as you expect. And, please make sure you’re using the latest version of JFugue, which at this point is Version 5.0.9.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement