1

我有一个线程来播放音频但是当我关闭表单时我想停止播放器播放音频文件我的线程运行方法是:

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;
  }
}    

问题是它没有像我想做的那样停止我的线程以及停止播放音频。我怎样才能做到这一点?请帮助我提前谢谢!

4

2 回答 2

0

移动这三行

 BGMusic.fis.close();
 BGMusic.bis.close();
 BGMusic.playplayer.close();      //want to close my player here

在一段时间关闭之后

 while(!Thread.currentThread().isInterrupted()){
    //stuff
 }

应该管用。就我而言,我更喜欢创建一个布尔值来检查线程是否应该退出并用于join()等待线程完成。

于 2013-05-15T15:07:22.100 回答
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);
}

   }

那是!你完全完成了茅草!

于 2013-05-15T15:38:36.627 回答