Tag Archives: Sequencer

Java Sequencer Quirk

I’m working on a music app that involves using Midi to trigger audio. Yesterday I wound up in a situation where after adding a new Track to my Sequence, I wasn’t receiving any of the MidiEvents that I added to the track. The problem, it turns out, is that the default Java Sequencer appears to cache all of the Tracks in a Sequence when you initially set the Sequence on the Sequencer using the setSequence method. If you modify the Sequence itself, as opposed to modifying the contents of the Tracks in the Sequence, the Sequencer won’t know about it until you call setSequence again. Just thought I’d throw this little tidbit out there, in case someone else runs into the same problem. Here’s some code to illustrate my point:

// make a sequence
Sequence s = new Sequence(Sequence.PPQ, 4);
 
// make a track in the sequence
Track t = s.createTrack();
 
// add midi events to the track
// ...
 
// make a sequencer
Sequencer seq = MidiSystem.getSequencer();
seq.open();
seq.setSequence(s);
seq.start();
 
// at this point, we can modify the Track
// and the Sequencer will pick up those new notes
// but if we do this:
Track t2 = s.createTrack();
// and then add notes to this track
// the Sequencer will NOT play these notes
// because it doesn't know about the track we just created
// we have to SET THE SEQUENCE AGAIN!
seq.setSequence(s);
// now the sequencer will play the notes in the track we just created.