Java MIDI 音序器永无止境
Posted
技术标签:
【中文标题】Java MIDI 音序器永无止境【英文标题】:Java MIDI sequencer never ends 【发布时间】:2020-01-05 10:56:09 【问题描述】:我正在运行教程中的一些 MIDI 代码,但程序永远不会终止。似乎 MIDI 音序器从未停止运行,即使它报告长度为 0.625 秒。
我是否需要做其他事情才能使音序器停止?
import javax.sound.midi.*;
public class MyMidiPlayer
public static void main(String[] args)
MyMidiPlayer player = new MyMidiPlayer();
player.setUpPlayer(4);
public void setUpPlayer(int numOfNotes)
try
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
Sequence sequence = new Sequence(Sequence.PPQ, 4);
Track track = sequence.createTrack();
for (int i = 0; i < numOfNotes; i++)
track.add(makeEvent(144, 1, i+48, 100, i));
track.add(makeEvent(128, 1, i+48, 100, i + 2));
sequencer.setSequence(sequence);
sequencer.setTempoInBPM(88);
System.out.println("Playing (length=" + sequencer.getMicrosecondLength()/1000000f + "s)...");
sequencer.start();
while (true)
// Never returns false, so the program never quits
if (!sequencer.isRunning())
sequencer.close();
System.exit(1);
catch (Exception ex)
ex.printStackTrace();
public MidiEvent makeEvent(int command, int channel, int note, int velocity, int tick)
MidiEvent event = null;
try
ShortMessage a = new ShortMessage();
a.setMessage(command, channel, note, velocity);
event = new MidiEvent(a, tick);
catch (Exception ex)
ex.printStackTrace();
return event;
【问题讨论】:
【参考方案1】:我打算删除它,但我会保留它并发布答案。看来您需要在while
循环中调用sequencer.getMicrosecondPosition()
。大概这会更新序列器类中的一些变量,然后当位置与getMicrosecondLength
返回的值匹配时,使isRunning
正确返回false
。
具体来说:
while (true)
if (!sequencer.isRunning())
sequencer.close();
System.exit(1);
sequencer.getMicrosecondPosition();
【讨论】:
以上是关于Java MIDI 音序器永无止境的主要内容,如果未能解决你的问题,请参考以下文章