简体   繁体   中英

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.

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()!

    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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM