我有这个简单的程序,它只使用MIDI播放一个音符。问题是,即使它播放了音符,程序仍在继续,但我不知道为什么。有什么帮助吗?
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
Sequence sequence = new Sequence(Sequence.PPQ, 1);
Track track = sequence.createTrack();
ShortMessage noteOnMsg = new ShortMessage();
noteOnMsg.setMessage(ShortMessage.NOTE_ON, 0, 60, 100);
ShortMessage noteOffMsg = new ShortMessage();
noteOffMsg.setMessage(ShortMessage.NOTE_OFF, 0, 60, 100);
track.add(new MidiEvent(noteOnMsg, 0));
track.add(new MidiEvent(noteOffMsg, 120));
sequencer.setSequence(sequence);
sequencer.start();
Thread.sleep(5000);
sequencer.stop();
答案 0 :(得分:1)
需要关闭Sequencer。一种选择是只将sequencer.close()
添加到代码的末尾,但由于Sequencer实现了AutoCloseable,更好的方法是将它放在try-with-resources子句中:
try (Sequencer sequencer = MidiSystem.getSequencer()) {
sequencer.open();
Sequence sequence = new Sequence(Sequence.PPQ, 1);
Track track = sequence.createTrack();
ShortMessage noteOnMsg = new ShortMessage();
noteOnMsg.setMessage(ShortMessage.NOTE_ON, 0, 60, 100);
ShortMessage noteOffMsg = new ShortMessage();
noteOffMsg.setMessage(ShortMessage.NOTE_OFF, 0, 60, 100);
track.add(new MidiEvent(noteOnMsg, 0));
track.add(new MidiEvent(noteOffMsg, 120));
sequencer.setSequence(sequence);
sequencer.start();
Thread.sleep(5000);
sequencer.stop();
}
答案 1 :(得分:-2)
您需要使用
if (sequencer != null && sequencer.isOpen()) {
sequencer.stop();
sequencer.setMicrosecondPosition(0);
}
我希望这对你有所帮助。