4

I'm trying to loop a MIDI sequence in a java game I'm making and I'm having some issues.

The current code I have does repeat the sequence, but there is a large delay between the end of the sequence and the restart. How can I eliminate this?

Here's my code:

try
    {
    // From file
        final Sequence sequence = MidiSystem.getSequence(new File("main menu.mid"));
        sequencer = MidiSystem.getSequencer();
        sequencer.open();
        sequencer.addMetaEventListener(new MetaEventListener() {
            public void meta(MetaMessage msg) {
                if (msg.getType() == 47) { // End of track
                    sequencer.setTickPosition(0);
                    try
                    {
                        sequencer.setSequence(sequence);
                    } catch(InvalidMidiDataException e) {e.printStackTrace();}
                    sequencer.start();
                }
            }
        });
        sequencer.setSequence(sequence);

    // Start playing
        sequencer.start();
    } catch (IOException e) {e.printStackTrace();}
      catch (MidiUnavailableException e) {e.printStackTrace();}
      catch (InvalidMidiDataException e) {e.printStackTrace();}

1 Answer 1

2

This source adapted from the Java Sound tag Wiki plays the MIDI without a 'long delay' between loops, which suggests to me that the delay you are hearing is part of the silent intro/outtro of the existing track.

import javax.sound.midi.*;
import javax.swing.JOptionPane;
import java.net.URL;

class LoopMidi {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://pscode.org/media/EverLove.mid");

        Sequence sequence = MidiSystem.getSequence(url);
        Sequencer sequencer = MidiSystem.getSequencer();

        sequencer.open();
        sequencer.setSequence(sequence);
        //sequencer.setLoopStartPoint(2000);
        //sequencer.setLoopEndPoint(4000);
        sequencer.setLoopCount(5);

        sequencer.start();
        JOptionPane.showMessageDialog(null, "Everlasting Love");
    }
}

The solution then lies in either:

  1. Trimming the MIDI track to remove those delays.
  2. Setting the loop points of the existing MIDI (as shown above, but commented out).
Sign up to request clarification or add additional context in comments.

3 Comments

I checked the MIDI files for trailing silence. There is none. The file ends when the sound ends.
Did you ever solve the problem? Did you try other MIDI files?
I did eventually get it to loop properly, but I haven't touched this code since early 2013 and none of it was in version control so at this point I have no idea what I did.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.