我正在尝试创建一个可以播放MIDI键盘音符的程序。我无法让整个程序工作,但我现在正在尝试创建一个较小的概念证明程序来尝试并解决它。
为此,我试图将.mid文件播放到键盘(卡西欧CTK-3000),MidiPlay可以播放键盘。问题是,当我尝试在我的程序中弹奏键盘时,它什么也没玩。我的代码如下:
public class midiOut {
public static void main(String[] args) throws IOException, MidiUnavailableException, InvalidMidiDataException
{
while(true) {
//List Midi Devices
MidiDevice.Info[] midiInfo = MidiSystem.getMidiDeviceInfo();
int i = 0;
for (MidiDevice.Info info : midiInfo) {
System.out.println(i + ": " +info.getName());
i+=1;
}
//Select Device
Scanner in = new Scanner(System.in);
int input = in.nextInt();
if(input == -1)
{
break;
}
//Get Device and Open it
MidiDevice selectedDevice = MidiSystem.getMidiDevice(midiInfo[input]);
System.out.println(selectedDevice.getDeviceInfo().getName());
selectedDevice.open();
//Get Sequencer and Receiver, load the File and start playing
Receiver receiver = selectedDevice.getReceiver();
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.getTransmitter().setReceiver(receiver);
sequencer.open();
sequencer.setSequence(MidiSystem.getSequence(new File("C:\\Users\\Harris Mirza\\Downloads\\PennyLane.mid")));
sequencer.start();
selectedDevice.close();
}
}
}
答案 0 :(得分:1)
意识到我的错误,我太早关闭了设备,在关闭前添加了一张支票,修改了代码:
import javax.sound.midi.*;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class midiOut {
public static void main(String[] args) throws IOException, MidiUnavailableException, InvalidMidiDataException
{
while(true) {
//List Midi Devices
MidiDevice.Info[] midiInfo = MidiSystem.getMidiDeviceInfo();
int i = 0;
for (MidiDevice.Info info : midiInfo) {
System.out.println(i + ": " +info.getName());
i+=1;
}
//Select Device
Scanner in = new Scanner(System.in);
int input = in.nextInt();
if(input == -1)
{
break;
}
//Get Device and Open it
MidiDevice selectedDevice = MidiSystem.getMidiDevice(midiInfo[input]);
System.out.println(selectedDevice.getDeviceInfo().getName());
selectedDevice.open();
//Get Sequencer and Receiver, load the File and start playing
Receiver receiver = selectedDevice.getReceiver();
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.getTransmitter().setReceiver(receiver);
sequencer.open();
sequencer.setSequence(MidiSystem.getSequence(new File("C:\\Users\\Harris Mirza\\Downloads\\Eight_bar_blues.mid")));
sequencer.start();
sequencer.addMetaEventListener(new MetaEventListener() {
@Override
public void meta(MetaMessage meta) {
if(meta.getType() == 47)
{
sequencer.close();
}
}
});
while (sequencer.isOpen()){}
}
}
}