我有一个播放音频的线程但是当我关闭表单时我想停止播放音频文件的播放器我的线程运行方法是:
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;
}
}
事情是它没有像我想做的那样停止我的线程以及停止播放音频。我怎样才能实现这一目标?请帮助我提前谢谢!
答案 0 :(得分:0)
移动这三行
BGMusic.fis.close();
BGMusic.bis.close();
BGMusic.playplayer.close(); //want to close my player here
在关闭之后
while(!Thread.currentThread().isInterrupted()){
//stuff
}
应该有效。就我而言,我更喜欢创建一个布尔值来检查线程是否应该退出并使用join()
等待线程完成。
答案 1 :(得分:0)
把它当作:
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类应该有以下内容: 即你应该使用volatile布尔变量来检查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);
}
}
那是的!你已经彻底完成了它!