[英]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.