4

我正在尝试使用 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)

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

4

2 回答 2

1

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

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

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

于 2018-06-25T19:00:15.687 回答
0

检查你的演员表:

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;
        }
    }
}   
于 2018-06-25T17:29:49.593 回答