[英]Stop the Player (JLayer) inside a java Thread
I have a thread to play an audio but when i close the form i want to stop the player playing the audio file my thread run method is: 我有一个线程可以播放音频,但是当我关闭表单时,我想停止播放器播放音频文件,我的线程运行方法是:
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);
}
}
My way of stop my player what i'm doing is: 我停止播放器的方式是:
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;
}
}
The thing is that it was not doing as i want to do to stop my thread as well as to stop playing the audio. 事实是,它并没有按照我想做的方式停止我的线程以及停止播放音频。 How can i achieve this?
我怎样才能做到这一点? Please help me Thanks in advance!
请帮助我,谢谢!
Moving these three lines 移动这三行
BGMusic.fis.close();
BGMusic.bis.close();
BGMusic.playplayer.close(); //want to close my player here
right after the while closes 一阵子关门之后
while(!Thread.currentThread().isInterrupted()){
//stuff
}
should work. 应该管用。 For my part I'd prefer to create a boolean value to check if the thread should exit and use
join()
to wait for the thread to finish. 就我而言,我更喜欢创建一个布尔值来检查线程是否应该退出,并使用
join()
等待线程完成。
put this as: 将此作为:
Thread audioplay=null;
start the thread normally! 正常启动线程! then!
然后!
if (audioplay != null) {
bg.Terminate();
playplayer.close();
try {
audioplay.join();
} catch (InterruptedException ex) {
//catch the exception
}
System.out.print("The thread has stopped");
}
your Thread class should have these: ie you should use a volatile Boolean variable to check in while()! 您的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);
}
}
That is! 那是! you're completely done thatch it !
您已经完全完成了草稿!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.