javax.sound.sampled.clip在播放声音之前终止

时间:2014-02-26 08:33:01

标签: java audio javax.sound.sampled

我很困惑为什么这会立即终止...到目前为止,调试器并没有真正的帮助..我确信代码正在全程运行。

import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;

/**
 * An example of loading and playing a sound using a Clip. This complete class
 * isn't in the book ;)
 */
public class ClipTest {

  public static void main(String[] args) throws Exception {

    // specify the sound to play
    // (assuming the sound can be played by the audio system)
    File soundFile = new File("C:\\Users\\Benny\\Desktop\\AudioSample\\Austin.wav");
    AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);

    // load the sound into memory (a Clip)
    DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
    Clip clip = (Clip) AudioSystem.getLine(info);
    clip.open(sound);
    // due to bug in Java Sound, explicitly exit the VM when
    // the sound has stopped.
    clip.addLineListener(new LineListener() {
      public void update(LineEvent event) {
        if (event.getType() == LineEvent.Type.STOP) {
          event.getLine().close();
          System.exit(0);
        }
      }
    });
    // play the sound clip
    clip.start();
  }
} 

1 个答案:

答案 0 :(得分:2)

clip.start()的调用导致声音在另一个线程上播放,即在“Java Sound Event Dispatcher”线程上播放。主线程正常进行,退出应用程序。

根据如何 确切地想要播放此片段,有不同的解决方案。通常,没有必要采取额外的预防措施。例如,在游戏中,您想要播放游戏中的声音,但是当游戏退出时,则不应再播放声音。通常情况下,你完全退出应用程序{ - 1}} - 特别是在任意剪辑播放完毕后不会...

但是,在此示例中,您可以使用System.exit(0)

CountDownLatch