我如何在java中关闭midi设备?我尝试重新初始化 MidiHandler 对象,但设备保持打开状态,直到程序终止。此外,如果我在程序运行时拔下我的 midi 控制器,它不会在重新连接后发送注释,即使在重新初始化之后也是如此。我必须再次终止并重新启动程序,才能使其正常工作。我对使用 midi 很陌生,所以我可能从根本上误解了整个概念。这是我到目前为止所拥有的:
public class MidiHandler {
MidiDevice device;
MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
public MidiHandler() {
for (int i = 0; i < infos.length; i++) {
try {
this.device = MidiSystem.getMidiDevice(this.infos[i]);
// does the device have any transmitters?
// if it does, add it to the device list
System.out.println(this.infos[i]);
// get all transmitters
List<Transmitter> transmitters = this.device.getTransmitters();
// and for each transmitter
for (int j = 0; j < transmitters.size(); j++) {
// create a new receiver
transmitters.get(j).setReceiver(
// using my own MidiInputReceiver
new MidiInputReceiver(this.device.getDeviceInfo()
.toString()));
}
Transmitter trans = this.device.getTransmitter();
trans.setReceiver(new MidiInputReceiver(this.device.getDeviceInfo()
.toString()));
this.device.open();
} catch (MidiUnavailableException e) {
}
}
}
public void close() {
}
public String getInfos() {
String infos = "";
for(int i = 0; i < this.infos.length; i++) {
infos += "\n" + this.infos[i] + " ";
}
return infos;
}
// tried to write my own class. I thought the send method handles an
// MidiEvents sent to it
public class MidiInputReceiver implements Receiver {
Synthesizer synth;
MidiChannel[] mc;
Instrument[] instr;
int instrument;
int channel;
public MidiInputReceiver(String name) {
try
{
patcher p = new patcher();
this.instrument = p.getInstrument();
this.channel = p.getChannel();
this.synth = MidiSystem.getSynthesizer();
this.synth.open();
this.mc = synth.getChannels();
instr = synth.getDefaultSoundbank().getInstruments();
this.synth.loadInstrument(instr[1]);
mc[this.channel].programChange(0, this.instrument);
}
catch (MidiUnavailableException e)
{
e.printStackTrace();
System.exit(1);
}
}
public void send(MidiMessage msg, long timeStamp) {
/*
* Use to display midi message
*/
for(int i = 0; i < msg.getMessage().length; i++) {
System.out.print("[" + msg.getMessage()[i] + "] ");
}
System.out.println();
if (msg.getMessage()[0] == -112) {
mc[this.channel].noteOn(msg.getMessage()[1], msg.getMessage()[2]+1000);
}
if (msg.getMessage()[0] == -128) {
mc[this.channel].noteOff(msg.getMessage()[1], msg.getMessage()[2]+1000);
}
}
public void close() {
}
}
主类只是实例化了一个 MidiHandler 并且工作正常,除了上面的问题。