我已经编写了一些基本代码,用于从外部MIDI键盘录制音符,并将它们按顺序存储在音轨中,保存该序列然后再播放。
代码工作正常,但是在敲击音符与合成器产生音符之间存在一定程度的延迟。我放置了一堆调试代码[忽略您不认识的方法调用,例如Debugging.info(),它们与问题无关]。我还输出了合成器的等待时间值,看起来是120000微秒。那就是我需要以某种方式降低的价值。
有没有办法做到这一点,或者我需要连接到其他外部合成器或减少延迟的东西吗?
我看着Midi device connection and latency无济于事。
代码:
try (
final Synthesizer synthesizer = MidiSystem.getSynthesizer();
final Sequencer sequencer = MidiSystem.getSequencer();
final MidiDevice midiInDevice = MidiSystem.getMidiDevice(MidiSystem.getMidiDeviceInfo()[1])
) {
synthesizer.open();
sequencer.open();
midiInDevice.open();
Debugging.trace("Synth Latency: " + synthesizer.getLatency());
midiInDevice.getTransmitter().setReceiver(sequencer.getReceiver());
midiInDevice.getTransmitter().setReceiver(synthesizer.getReceiver());
final Receiver receiver = new Receiver() {
@Override
public void send(final MidiMessage message, final long timeStamp) {
Debugging.info("Message [" + timeStamp + "]: " + message);
}
@Override
public void close() {
Debugging.info("Closing...");
}
};
midiInDevice.getTransmitter().setReceiver(receiver);
Debugging.trace("MIDI In: " + midiInDevice.getDeviceInfo().getName());
final Sequence sequence = new Sequence(Sequence.PPQ, 96);
sequencer.setSequence(sequence);
final Track track = sequence.createTrack();
sequencer.setTickPosition(0);
sequencer.recordEnable(track, 0);
Debugging.trace("Recording Started");
sequencer.startRecording();
Sleeper.sleep(20, TimeUnit.SECONDS);
sequencer.stopRecording();
sequencer.recordDisable(track);
receiver.close();
Debugging.trace("Recording Stopped");
MidiUtil.save(new File("/Media/Midi/test.mid"), sequence);
Sleeper.sleep(1, TimeUnit.SECONDS);
MidiUtil.allNotesOff(synthesizer);
}
final Sequence loadedSequence = MidiUtil.load(new File("/Media/Midi/test.mid"));
MidiUtil.playSequence(loadedSequence);