Java Midi - How to get notes from midi whilst it&#

2020-02-06 18:06发布

问题:

I've searched for a while now, and can't find an answer for what I want to do.

I want to play a midi file, and display the notes on the screen as it plays. When a note stops playing, it should disappear off the screen.

I can play a midi with a sequencer, but have no idea of how to get the notes its playing, or when it stops playing a note.

I've looked into ControllerEventListeners and MetaEventListeners, but still don't know how to do this.

Any help would be appreciated.

回答1:

This is a FAQ.
Connect you own Receiver to the sequencer's Transmitter.

See the DumpReceiver in the MidiPlayer for an example.



回答2:

That's what you should do:

You have to implement Receiver and then

sequencer = MidiSystem.getSequencer();
sequencer.open();
transmitter = sequencer.getTransmitter();
transmitter.setReceiver(this);

and after that, the next method will be triggered every time an event occurs:

@Override
public void send(MidiMessage message, long timeStamp) {
    if(message instanceof ShortMessage) {
        ShortMessage sm = (ShortMessage) message;
        int channel = sm.getChannel();

        if (sm.getCommand() == NOTE_ON) {

            int key = sm.getData1();
            int velocity = sm.getData2();
            Note note = new Note(key);
            System.out.println(note);

        } else if (sm.getCommand() == NOTE_OFF) {

            int key = sm.getData1();
            int velocity = sm.getData2();
            Note note = new Note(key);
            System.out.println(note);
        } else {
            System.out.println("Command:" + sm.getCommand());
        }
    }
}

and if you want, you can use this class too:

public class Note {

    private static final String[] NOTE_NAMES = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"};

    private String name;
    private int key;
    private int octave;

    public Note(int key) {
        this.key = key;
        this.octave = (key / 12)-1;
        int note = key % 12;
        this.name = NOTE_NAMES[note];
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof Note && this.key == ((Note) obj).key;
    }

    @Override
    public String toString() {
        return "Note -> " + this.name + this.octave + " key=" + this.key;
    }
}