java循环播放_java中循环播放midi

该博客介绍了一个Java实现的MIDI音乐播放器,它可以循环并随机播放指定目录下的MIDI文件。代码创建了一个Sequencer实例,并加载多个MID文件到一个HashMap中,然后在一个独立的线程中无限循环随机选择并播放MIDI文件,每次间隔10秒。
摘要由CSDN通过智能技术生成

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注册。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值