Search code examples
javaloopsmidi

How to loop a Midi sequence Java


I am fairly new to Java programming, and would like to know how to properly loop a MIDI sequence whilst a game is playing. I have some code and I know that I should use setLoopCount() in order to do it but am unsure how to implement it.

Here is the code I have so far

Sequencer myseq; 
myseq = MidiSystem.getSequencer(); 
myseq.open();
File myMidiFile = new File("sounds/music.midi");
Sequence supersequence = MidiSystem.getSequence(myMidiFile);
myseq.setSequence(supersequence);
myseq.start(); 

Any help is appreciated.


Solution

  • There is a good (but old) book about java game development: http://www.brackeen.com/javagamebook/ The source code is available at the website. Check out the chapter 4... In the SoundManagerTest.java file, you will find an example about looping midi sounds. I hope it is not too outdated.

    Btw: There seems to be an issue with MIDI looping and Java 5. Have a look at the end of the page:

    Sound Issues in Java 5 and Java 6.

    Sun updated the sound engine in Java 5 which led to a few problems. Here are the fixes: MIDI music doesn't loop. Add this line (in bold) in MidiPlayer.java:

    public void meta(MetaMessage event) {
      if (event.getType() == END_OF_TRACK_MESSAGE) {
       if (sequencer != null && sequencer.isOpen() && loop) {
           sequencer.setTickPosition(0);
           sequencer.start();
       }
      }
    }