The example below brings up a Swing JFrame, and then loads and plays a MIDI file.
The trick to having the MIDI loop "forever" is the call to sequencer.setLoopCount(Integer.MAX_VALUE);
package com.stackoverflow.questions;
import java.awt.Dimension;
import java.awt.Point;
import java.net.URL;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MidiJFrame extends JFrame {
public MidiJFrame()
{
super("Window Title");
startMidi();
add( new JLabel("Midi JFrame", JLabel.CENTER) );
setSize( new Dimension(300, 100) );
setLocation( new Point(100, 200) );
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String [] args)
{
MidiJFrame app = new MidiJFrame();
}
private void startMidi()
{
try
{
URL url = getClass().getResource("/samples/avicii-wake_me_up.mid");
Sequence sequence = MidiSystem.getSequence(url);
// the sequence can also be obtained from the local filesystem
// Sequence sequence = MidiSystem.getSequence(new File("path/to/midi/file.mid"));
// Create a sequencer for the sequence
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.setSequence(sequence);
// play the midi a semi-infinate loop
sequencer.start();
sequencer.setLoopCount(Integer.MAX_VALUE);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}