在这里,我有一段简单的代码,可以使用自定义的Soundbank以固定的间隔播放10个音符,但结果不是以正常的速度播放,或者某些东西引入了显着的延迟。难道我做错了什么 ?有没有"热身"时间?
我在Ubuntu上使用OpenJDK 8。
谢谢:)。
import java.io.File;
import java.io.IOException;
import javax.sound.midi.*;
public class MidiTest
{
static public void main(String[] args) throws MidiUnavailableException, InvalidMidiDataException, IOException
{
Sequence sequence = new Sequence(Sequence.PPQ, 1000);
Track track = sequence.createTrack();
for (int i = 0; i < 10; i++)
{
ShortMessage noteOn = new ShortMessage(ShortMessage.NOTE_ON , 0, 50, 100);
ShortMessage noteOff = new ShortMessage(ShortMessage.NOTE_OFF, 0, 50, 100);
int noteOnTime = 1000 * i;
int noteOffTime = 1000 * (i + 1);
track.add(new MidiEvent(noteOn , noteOnTime ));
track.add(new MidiEvent(noteOff, noteOffTime));
}
Soundbank soundbank = MidiSystem.getSoundbank(new File("titanic.sf2"));
Synthesizer synth = MidiSystem.getSynthesizer();
synth.open();
synth.loadAllInstruments(soundbank);
synth.getChannels()[0].programChange(1);
Sequencer sequencer = MidiSystem.getSequencer(false);
sequencer.open();
sequencer.setSequence(sequence);
sequencer.setTempoInBPM(120);
sequencer.addMetaEventListener(new MetaEventListener() {
public void meta(MetaMessage msg)
{
if (msg.getType() == 47) {
// end of sequence
System.exit(0);
}
}
});
sequencer.getTransmitter().setReceiver(synth.getReceiver());
sequencer.start();
}
}
答案 0 :(得分:0)
首先loadAllInstruments然后打开合成器:
synth.loadAllInstruments(soundbank);
synth.open();