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

余生颓废 提交于 2019-12-01 12:31:48

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

See the DumpReceiver in the MidiPlayer for an example.

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