0

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

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();
  }
} 
4

1 回答 1

2

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

根据您想要播放此剪辑的方式和时间,有不同的解决方案很多时候,不需要额外的预防措施。例如,在游戏中,您想播放游戏中的声音,但当游戏退出时,不应再播放任何声音。通常,您根本不会退出应用程序System.exit(0)- 尤其是在任意剪辑完成播放后...

但是,在此示例中,您可能会使用CountDownLatch.

final CountDownLatch clipDone = new CountDownLatch(1);
clip.addLineListener(new LineListener() {
    @Override
    public void update(LineEvent event) {
        if (event.getType() == LineEvent.Type.STOP) {
            event.getLine().close();
            clipDone.countDown();
        }
    }
});
// play the sound clip and wait until it is done
clip.start();
clipDone.await();
于 2014-02-26T11:32:00.407 回答