[英]Stop the Player (JLayer) inside a java Thread
我有一个线程可以播放音频,但是当我关闭表单时,我想停止播放器播放音频文件,我的线程运行方法是:
public static Player playplayer;
public static FileInputStream fis;
public static BufferedInputStream bis;
public void run(){
while(!Thread.currentThread().isInterrupted()){
try{
String file="E://Net Beans Work Space//The Imran's Regression"
+ "//src//imranregression//audio//iron man.mp3";
fis= new FileInputStream(file);
bis= new BufferedInputStream(fis);
playplayer = new Player(bis);
playplayer.play();
}catch(Exception e){
System.out.print("ERROR "+e);
}
}
我停止播放器的方式是:
private void formWindowClosing(java.awt.event.WindowEvent evt) {
try{
BGMusic.fis.close();
BGMusic.bis.close();
BGMusic.playplayer.close(); //want to close my player here
audioplay.interrupt(); //stopping my thread here
}catch(Exception e){
return;
}
}
事实是,它并没有按照我想做的方式停止我的线程以及停止播放音频。 我怎样才能做到这一点? 请帮助我,谢谢!
移动这三行
BGMusic.fis.close();
BGMusic.bis.close();
BGMusic.playplayer.close(); //want to close my player here
一阵子关门之后
while(!Thread.currentThread().isInterrupted()){
//stuff
}
应该管用。 就我而言,我更喜欢创建一个布尔值来检查线程是否应该退出,并使用join()
等待线程完成。
将此作为:
Thread audioplay=null;
正常启动线程! 然后!
if (audioplay != null) {
bg.Terminate();
playplayer.close();
try {
audioplay.join();
} catch (InterruptedException ex) {
//catch the exception
}
System.out.print("The thread has stopped");
}
您的Thread类应具有以下功能:即,您应使用易失性布尔变量来检入while()!
private volatile boolean running = true;
public void Terminate() {
running = false;
}
public void run(){
while(running){
try{
String file="E://Net Beans Work Space//The Imran's Regression"
+ "//src//imranregression//audio//iron man.mp3";
fis= new FileInputStream(file);
bis= new BufferedInputStream(fis);
playplayer = new Player(bis);
playplayer.play();
}catch(Exception e){
System.out.print("ERROR "+e);
}
}
那是! 您已经完全完成了草稿!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.