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:
[snip java]
// 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.
[/snip]
A question about this… Let’s say you were trying to modify the sequence in real time. I have a gui represenation of a sequence..and when i click on a cell to fill it in (like in a piano roll) , i basically rebuild the sequence over again then say setSequence. but it causes the sequencer to restart from the beginning. i would rather be able to just add the new events without having the sequencer restart.
So, re-reading my post, it sounds like what you should do is create all of the Tracks that you intend to put note events in and hang on to those. Then you can add and remove notes in each track based on user-input and the sequence should pick up those changes with no problems.
thanks for the reply. i’ve done something to that effect,..where when the user clicks on the piano roll cell, the program makes note of the tick position and then rebuilds the sequence and then does setsequence and settickposition to the time i want it to be. but it always sounds glitchy though. even though it is at least at the correct tick position, it’s never a smooth thing. do i need to keep some sortof timer going?