package aquar.loop.music;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
public class LoopMusic implements Runnable{
private Sequencer midi;
private String[] names ={".\\sound\\1.mid",".\\sound\\2.mid",".\\sound\\3.mid",".\\sound\\4.mid",".\\sound\\5.mid"};
private int i;//播放歌曲计数
private Map map;
public LoopMusic() {//constructor
initMap();
new Thread(this).start();
}
private void initMap(){//initiate the map
try {
map = new Hashtable();
midi = MidiSystem.getSequencer();//only one instance of squencer.
midi.open();//open a device for play.
for (String s: names) {
try {
Sequence s1 = MidiSystem.getSequence(new File(s));//read a midi file.
map.put(s, s1);//put the midi file into the map.
} catch (InvalidMidiDataException ex) {
Logger.getLogger(LoopMusic.class.getName()).log(Level.SEVERE,null,ex);
// TODO: handle exception
} catch (IOException ex) {
Logger.getLogger(LoopMusic.class.getName()).log(Level.SEVERE,null,ex);
}
}
} catch (MidiUnavailableException ex) {
Logger.getLogger(LoopMusic.class.getName()).log(Level.SEVERE,null,ex);
// TODO: handle exception
}
}
private void createPlayer(String name){
try {
System.out.println(name);
System.out.println(map.get(name));
Sequence se = map.get(name);//read a midi file from the map.
midi.setSequence(se);//set current midi file.
midi.start();//play the midi file.
} catch (InvalidMidiDataException ex) {
Logger.getLogger(LoopMusic.class.getName()).log(Level.SEVERE,null,ex);
}
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
new LoopMusic();
}
@Override
public void run() {
while (true) {
try {
System.out.println("换文件了。"+(++i));
String name = names[(int)(Math.random()*names.length)];//read a midi file randomly
createPlayer(name);//play a midi file.
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(LoopMusic.class.getName()).log(Level.SEVERE,null,ex);
}
}
}
}
本文使用Blog_Backup未注册版本导出,请到soft.pt42.com注册。