[英]Java Midi - How to get notes from midi whilst it's playing
我已經搜索了一段時間,但找不到想要做什么的答案。
我想播放一個MIDI文件,並在播放時在屏幕上顯示筆記。 當音符停止播放時,它應該會從屏幕上消失。
我可以使用音序器演奏Midi,但不知道如何演奏它的音符,或者何時停止演奏音符。
我已經研究了ControllerEventListeners和MetaEventListeners,但仍然不知道該怎么做。
任何幫助,將不勝感激。
這是一個常見問題解答 。
將您自己的接收器連接到音序器的發射器。
有關示例,請參見MidiPlayer中的DumpReceiver 。
那就是你應該做的:
您必須實現Receiver
然后
sequencer = MidiSystem.getSequencer();
sequencer.open();
transmitter = sequencer.getTransmitter();
transmitter.setReceiver(this);
之后,每次發生事件時都會觸發下一個方法:
@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());
}
}
}
如果需要,您也可以使用此類:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.