java线程怎么添加音乐,在Java问题中使用JLayer在线程中仅播放一个mp3文件

I'm working at an Audio Player, which is written in Java with GUI. For playing the mp3 files, I've chosen JLayer library from javazoom because I saw it's very popular and used. I made the GUI, managed to play the selected mp3 file from the playlist.

My problem is that if I press many times on the play button or on the file from the playlist it will start playing the song as many times as I press it and I want to play it one the same thread ; if I press again play button I want to play again not to start the same song while the current one is playing .

Here is my code which play the mp3 file:

public class Playing implements Runnable{

private Player mp3Player;

private Thread playerThread;

public void createPlayer(FileInputStream file) throws JavaLayerException{

mp3Player = new Player(file);

playerThread = new Thread(this);

playerThread.start();

}

@Override

public void run(){

try {

mp3Player.play();

}

catch (JavaLayerException ex) {

Logger.getLogger(Playing.class.getName()).log(Level.SEVERE, null, ex);

}

}

This is my method for the play button:

public void createPlayButton(){

play = new JButton();

playButton = new ImageIcon("D:/Audio Player/Images/playButton.png");

play.setBounds(125, 100, 50, 50);

play.setIcon(playButton);

play.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

for (int i = 0; i < select.getFilesPath().size(); i++){

if (select.getFilesPath().get(i).toString().contains(playlistBody.getSongName())){

try {

mp3Player.createPlayer(new FileInputStream(new File(select.getFilesPath().get(i).toString())));

} catch (JavaLayerException ex) {

Logger.getLogger(PlayerBody.class.getName()).log(Level.SEVERE, null, ex);

} catch (FileNotFoundException ex) {

Logger.getLogger(PlayerBody.class.getName()).log(Level.SEVERE, null, ex);

}

}

}

}

});

}

I mention that I'm new to multithreading, so dont be so hard on me. If I cannot do this with JLayer, please recommend me a good library with which I can play mp3 files. Thank you in advance and I'm waiting for your suggestions.

解决方案

I fixed my issue with the threads; I'll put the solution, maybe will help someone.

static int fileRunning = 0;

public void playMp3(FileInputStream file) throws JavaLayerException{

if (fileRunning == 0){

mp3Player = new Player(file);

playerThread = new Thread(this);

playerThread.start();

fileRunning = 1;

}

}

So the main idea is that when I start playing a song, that int will take value 1, and it won't be 0, so no more threads can be made.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值