MidiSystem.getMidiDevice(...) returns 意外 class

MidiSystem.getMidiDevice(...) returns unexpected class

我正在尝试使用 javax.sound.midi 编写一个简单的程序,该程序读取、编辑然后通过 FluidSynth 播放 midi 文件。这是我的代码片段:

  Synthesizer synth;

  // Look through the available midi devices for a software synthesizer
  MidiDevice.Info[] deviceInfo = MidiSystem.getMidiDeviceInfo();

  for(MidiDevice.Info currentDevice : deviceInfo){
    if(currentDevice.getName().matches("FluidSynth virtual port.*"))
        synth = (Synthesizer) MidiSystem.getMidiDevice(currentDevice);
  }   

  // If FluidSynth is not found, use default synth
  if(synth == null){
    synth = MidiSystem.getSynthesizer();
    System.out.println("Using default synth");
  }

  // Do stuff with synth

代码编译成功,但是当我运行它时,我得到以下异常:

 Exception in thread "main" java.lang.ClassCastException: java.desktop/com.sun.media.sound.MidiOutDevice cannot be cast to java.desktop/javax.sound.midi.Synthesizer
    at SynthesizerDemo.main(SynthesizerDemo.java:49)

我期待合成器 class 返回,但我不明白 com.sun.media.sound.MidiOutDevice class 是什么。如果我将合成器切换到 MidiDevice class,播放会正常,但我无法访问 Synthesizer class 中的所有方法。知道我缺少什么吗?

检查你的演员阵容:

for(MidiDevice.Info currentDevice : deviceInfo){
    if(currentDevice.getName().matches("FluidSynth virtual port.*")) {
        MidiDevice device = MidiSystem.getMidiDevice(currentDevice);
        if (device instanceof Synthesizer) {
            synth = (Synthesizer) MidiSystem.getMidiDevice(currentDevice);
            break;
        }
    }
}   

Synthesizer 接口由 Java 中实现的合成器使用,可以通过该接口控制。

FluidSynth 不是用 Java 编写的,也没有实现该接口。从 JVM 的角度来看,FluidSynth 看起来就像任何其他 MIDI 端口。

要控制 FluidSynth,您必须发送正常的 MIDI 消息。