java使用插件播放mp3,同时只播放一首歌
程序员文章站
2022-03-04 17:40:04
...
再次学习synchronized的使用,实现一个mp3的简易播放
其中使用的插件是jl1.0.1.jar,在哪下我就懒的搜了。主要还是记录一下synchronized的使用,加强印象。
因为只同步了其中的播放方法,所以没被同步的会被先执行。
package other;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
public class MediaTest {
private long timeTarget;
private long time;
private Player player;
int[][] dateValue = {{2017,11,05,13,52,10},{2017,11,05,13,57,10}};
private static String musicDirectory = "D:/CloudMusic/";
private static String[] musicPath = {musicDirectory+"谢容儿 - 你不配.mp3",musicDirectory+"艾敬 - 做你的雪莲.mp3"};
public void Mp3(String audio) throws JavaLayerException{
try{
BufferedInputStream buff = new BufferedInputStream(new FileInputStream(audio));
player = new Player(buff);
Thread t = new Thread(()->{
System.out.println(Thread.currentThread().getName()+"播放中" + audio);
try {
synchronized(this){
System.out.println("进入线程同步,等待播放完当前这首歌才播放下一首");
player.play();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
t.start();
System.out.println("线程已启动");
}catch(IOException io){
io.printStackTrace();
}
}
public void alarmPlay(String[] musicPath) throws InterruptedException, JavaLayerException{
Calendar c = Calendar.getInstance(Locale.CHINA);
time = System.currentTimeMillis();
System.out.println("没设置指定日期之前:"+time);
//设置目标时间,只有月是0-11
// c.set(2017, 11, 05, 13, 25, 10);
for(int i=0; i< dateValue.length; i++){
c.set(dateValue[i][0], dateValue[i][1], dateValue[i][2], dateValue[i][3], dateValue[i][4], dateValue[i][5]);
timeTarget = c.getTimeInMillis();
System.out.println("设置指定日期之后"+timeTarget);
while(true){
time = System.currentTimeMillis();
if(time < timeTarget){
Thread.sleep(10000L);
System.out.println("距离指定时间还差"+(timeTarget -(time+10000L))/1000+"s");
}else{
System.out.println("else中的:"+time);
System.out.println(c.get(Calendar.YEAR) +"-"+ (c.get(Calendar.MONTH)+1) +"-"+
c.get(Calendar.DATE)+" " + c.get(Calendar.HOUR_OF_DAY)+":" + c.get(Calendar.MINUTE)+":"
+c.get(Calendar.SECOND));
Mp3(musicPath[i]);
break;
}
}
}
}
public static void main(String[] args) throws InterruptedException, JavaLayerException {
MediaTest mt = new MediaTest();
mt.alarmPlay(musicPath);
}
}
上一篇: 一天一首歌
下一篇: vue获取dom添加样式