【问题标题】:Java clip.open hangs indefinitelyJava clip.open 无限期挂起
【发布时间】:2016-06-22 02:56:05
【问题描述】:

我正在尝试打开一个 .wav 文件并使用剪辑播放它。但是当我调用 myClip.open(...) 时,线程冻结并且永远不会恢复。不会抛出任何错误。这是我的代码的简单版本:

try {
    AudioInputStream mySound = AudioSystem.getAudioInputStream(new File("sounds/myAudioFile.wav"));
    myClip = AudioSystem.getClip();
    myClip.open(mySound); //This is where it hangs
    myClip.start(); //This is never executed
} catch (Exception e) {e.printStackTrace();}

编辑: 我的代码的替代版本(也不起作用):

Clip myClip = null;

new Thread(new Runnable() {
     public void run() {
          try {
              AudioInputStream mySound = AudioSystem.getAudioInputStream(new File("sounds/myAudioFile.wav"));
              myClip = AudioSystem.getClip();
              System.out.println("Before open");
              myClip.open(mySound); //This is where it hangs
              System.out.println("After open"); //never executed
              //This thread runs indefinitely, whether or not clip.start() is called
          } catch (Exception e) {e.printStackTrace();}
     }
}).start();

try{  Thread.sleep(1000);  }catch(Exception e){} //give it a second to open

myClip.start(); //Executed, but doesn't make a sound
System.out.println("Started clip");

输出:

Before open
Started clip

我知道是什么原因造成的,但我想不出办法让线程永远冻结。它冻结是因为我计算机上的声音驱动程序偶尔会停止工作,并阻止任何程序的任何声音播放。我只需要一些方法来强制 clip.open 方法(或线程)在大约 2 到 3 秒后超时。 在另一个线程中调用 clip.start() 可以工作,但由于剪辑尚未打开,因此不会播放任何声音。并且包含 clip.open(...) 的线程将永远运行,即使在调用 clip.start() 之后也是如此。

【问题讨论】:

  • 尝试写在一个线程中。否则它会阻塞你的主线程,感觉就像冻结一样。

标签: java audio freeze javax.sound.sampled


【解决方案1】:
public static synchronized void playSound(final String url) {
  new Thread(new Runnable() {
  // The wrapper thread is unnecessary, unless it blocks on the
  // Clip finishing; see comments.
    public void run() {
      try {
        Clip clip = AudioSystem.getAudioInputStream(new File("sounds/myAudioFile.wav"));       // you can pass it in url
        clip.open(inputStream);
      } catch (Exception e) {
        System.err.println(e.getMessage());
      }
    }
  }).start();
}

还有一点: 你还没有开始你的剪辑。 使用 clip.start() 在这种情况下,您不必使用不同的线程,因为 clip.start() 会自己生成一个新线程。

【讨论】:

  • 这确实解决了我的冻结问题,但它也创建了一个永远不会结束的新线程。我想这不是问题,对吧?
  • 我已经写了一种方法来避免这种情况。一旦你使用clip.start(),它就会产生一个新线程。代码中的实际问题是您只是打开剪辑但从未启动它。所以它等待剪辑开始。
  • 这可能会有所帮助:(虽然我不确定它是否能解决您的问题):stackoverflow.com/questions/5241822/…
猜你喜欢
  • 2017-06-29
  • 2011-05-07
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
  • 2019-08-01
  • 1970-01-01
相关资源
最近更新 更多