java - 在 java 线程内停止播放器 (JLayer)

标签 java multithreading audio media-player

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

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

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

最佳答案

把它写成:

 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 boolean 变量来 checkin 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);
}

   }

就是这样!你已经完全完成了!

关于java - 在 java 线程内停止播放器 (JLayer),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16568173/

相关文章:

java - 与嵌入式 Tomcat 8 共享类加载器

java - 在不创建事务实例的情况下使用 hibernate 在数据库中进行插入

java - 如何在主线程下拦截可运行的创建和执行以使用AspectJ填充上下文流数据

python - python中spacy的多线程训练

audio - 无法使用HTML5音频元素在Grav中查找媒体文件

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java - 如何在maven应用程序中使用heroku环境变量绑定(bind)http服务器

c++ - OMP部分中的线程数

java - 关于 Java Sound API 的一些问题

python - 在后台更改 Windows 10 应用程序音频混合(最好使用 Python)