2014-03-03 29 views
1

我想添加一個midi文件到我的JFrame中,這樣當它啓動時,音樂將永遠循環播放。其他教程沒有爲我工作。如何將一個midi文件添加到JFrame?

public void LoopSound() throws LineUnavailableException{ 
    Clip clip = AudioSystem.getClip(getClass().getResource("/pokemontrivia/VioletCity.mid")); 
} 
+0

有你閱讀與http://stackoverflow.com/questions/380103/simple-java-midi-example-not-producing-any-sound MIDI問題?你有嘗試過這些嗎? –

回答

0

下面的示例顯示了一個Swing JFrame,然後加載並播放一個MIDI文件。

讓MIDI循環「永遠」的技巧是對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(); 
    }   
} 



}