Java Midi - How to get notes from midi whilst it's playing

泪湿孤枕 提交于 2019-12-01 10:09:40

问题


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;
    }
}


来源:https://stackoverflow.com/questions/26266411/java-midi-how-to-get-notes-from-midi-whilst-its-playing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!