我有一个简单的程序,使用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();

最佳答案

定序器需要关闭。一种选择是只在代码的末尾添加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();
}

07-24 21:19