java jl循环播放音乐,Java Jlayer Mp3 Player-如何重复和停止播放歌曲

I have problem with mp 3 player. I'm using jLayer.

This is my code

private void formWindowOpened(java.awt.event.WindowEvent evt) {

new Thread (){

public void run(){

try

{

Player prehravac;

FileInputStream buff = new FileInputStream(Okno.filename);

prehravac = new Player(buff);

prehravac.play();

if (prehravac != null)

{

prehravac.play();

}

}

catch(Exception e)

{

}

}

}.start();

}

In my application I need to play song from the beginning to the end. So when song ends I need to start it again and when window closes I want to stop this song...

解决方案

JLayer does not support continuous play, so you have to use a loop to repeatedly start a new player after the old one finished. For example:

try

{

do

{

FileInputStream buff = new FileInputStream(Okno.filename);

prehravac = new AdvancedPlayer(buff );

prehravac .play();

}while(loop);

}

catch(Exception ioe)

{

//TODO error handling

}

with loop being a boolean you can set true or false in a different method depending on if you want it to be played just once or repeatedly.

If you want to access the thread later you should at least declare it to a variable. Even better is writing a seperate class that extends thread. Doing so you can add method to the thread you can later call.

For your code it might look something like that:

import java.io.*;

import javazoom.jl.player.*;

public class MyAudioPlayer extends Thread {

private String fileLocation;

private boolean loop;

private Player prehravac;

public MyAudioPlayer(String fileLocation, boolean loop) {

this.fileLocation = fileLocation;

this.loop = loop;

}

public void run() {

try {

do {

FileInputStream buff = new FileInputStream(fileLocation);

prehravac = new Player(buff);

prehravac.play();

} while (loop);

} catch (Exception ioe) {

// TODO error handling

}

}

public void close(){

loop = false;

prehravac.close();

this.interrupt();

}

}

With this you can simply create the Thread when and wherever you want like this:

private MyAudioPlayer thePlayer;

[... some class code here...]

public void yourMethod(){

thePlayer = new MyAudioPlayer("path of the music file", true);

thePlayer.start();

}

and if you want to get rid of it at some point call thePlayer.close();

Note that thePlayer should be an instance variable so you can reuse it again. If you only declare it within a method it will disappear after the method is finished.

Hope this helps.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值