无法在 Java MIDI 程序中更改乐器,InvalidMidiDataException:channel 超出范围
Can't change instrument in Java MIDI program, InvalidMidiDataException:channel out of range
我无法使用 javax.sound.midi.ShortMessage.setMessage() 方法更改乐器。通道 0-15 是钢琴,不包括 9 是鼓。但是8-15应该是半音阶打击乐。当我将频道设置为 16 或更多(范围从 0 到 127)时,我得到 javax.sound.midi.InvalidMidiDataException: channel out of range: 16。拜托,我该如何解决这个问题?
import javax.sound.midi.*;
public class TestMidi{
public void play(){
try{
Sequencer player = MidiSystem.getSequencer();
System.out.println("Sequencer created succesfully.");
player.open();
Sequence s = new Sequence(Sequence.PPQ, 4);
Track track = s.createTrack();
addShortMessage(track,1,192,1,102,0);
addShortMessage(track,1,144,1,44,100);
addShortMessage(track,16,128,1,44,100);
player.setSequence(s);
player.start();
} catch(Exception e){
System.out.println("Fail.");
e.printStackTrace();
}
}
public static void main(String[] args) {
TestMidi tm = new TestMidi();
tm.play();
}
void addShortMessage(Track track, long tick, int command, int channel, int data1, int data2) throws Exception {
ShortMessage msg = new ShortMessage(command, channel, data1, data2);
MidiEvent event = new MidiEvent(msg, tick);
track.add(event);
}
}
频道编号从 0 到 15。每个频道都可以有自己的乐器(通过发送 Program Change 消息)。
此代码向轨道添加两条消息。如果要添加第三条消息,则必须使用第三个对象调用 track.add()
。
使用这样的辅助函数可以更轻松地添加事件:
void addShortMessage(Track track, long tick,
int command, int channel, int data1, int data2) {
ShortMessage msg = new ShortMessage(command, channel, data1, data2);
MidiEvent event = new MidiEvent(msg, tick); //edited here
track.add(event);
}
我无法使用 javax.sound.midi.ShortMessage.setMessage() 方法更改乐器。通道 0-15 是钢琴,不包括 9 是鼓。但是8-15应该是半音阶打击乐。当我将频道设置为 16 或更多(范围从 0 到 127)时,我得到 javax.sound.midi.InvalidMidiDataException: channel out of range: 16。拜托,我该如何解决这个问题?
import javax.sound.midi.*;
public class TestMidi{
public void play(){
try{
Sequencer player = MidiSystem.getSequencer();
System.out.println("Sequencer created succesfully.");
player.open();
Sequence s = new Sequence(Sequence.PPQ, 4);
Track track = s.createTrack();
addShortMessage(track,1,192,1,102,0);
addShortMessage(track,1,144,1,44,100);
addShortMessage(track,16,128,1,44,100);
player.setSequence(s);
player.start();
} catch(Exception e){
System.out.println("Fail.");
e.printStackTrace();
}
}
public static void main(String[] args) {
TestMidi tm = new TestMidi();
tm.play();
}
void addShortMessage(Track track, long tick, int command, int channel, int data1, int data2) throws Exception {
ShortMessage msg = new ShortMessage(command, channel, data1, data2);
MidiEvent event = new MidiEvent(msg, tick);
track.add(event);
}
}
频道编号从 0 到 15。每个频道都可以有自己的乐器(通过发送 Program Change 消息)。
此代码向轨道添加两条消息。如果要添加第三条消息,则必须使用第三个对象调用 track.add()
。
使用这样的辅助函数可以更轻松地添加事件:
void addShortMessage(Track track, long tick,
int command, int channel, int data1, int data2) {
ShortMessage msg = new ShortMessage(command, channel, data1, data2);
MidiEvent event = new MidiEvent(msg, tick); //edited here
track.add(event);
}