gpt4 book ai didi

java - 为什么我的 MIDI 程序没有完成/关闭?

转载 作者:搜寻专家 更新时间:2023-11-01 03:56:31 25 4
gpt4 key购买 nike

我有这个简单的程序,它使用 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 需要关闭。一种选择是将 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();
}

关于java - 为什么我的 MIDI 程序没有完成/关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40250253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com