1

I am trying to add a midi file to my JFrame so that when it starts up, the music plays in a loop forever. Other tutorials have not worked for me.

public void LoopSound() throws LineUnavailableException{
    Clip clip = AudioSystem.getClip(getClass().getResource("/pokemontrivia/VioletCity.mid"));
}
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
  • have you read the problem with midi on http://stackoverflow.com/questions/380103/simple-java-midi-example-not-producing-any-sound ? have you tried anything of that? – Martin Frank Mar 04 '14 at 07:11

1 Answers1

0

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();
    }        
}



}
onebeartoe
  • 135
  • 1
  • 8