2014-02-26 82 views
0

我很困惑,为什么这会直接终止...调试器迄今一直没有真正的帮助..我相信代码运行的整个方式通过。javax.sound.sampled.clip在播放声音之前终止

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

回答

2

clip.start()调用导致要在不同的线程播放的声音,即在“Java声音事件调度”线程。主线程正常进行,应用程序退出。

根据如何正是你想要播放这个片段,也有不同的解决方案。通常,不需要额外的预防措施。例如,在游戏中,您想玩游戏中的声音,但是当游戏退出时,则不应播放更多声音。通常,你会不会退出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(); 
+0

好的很好,谢谢。 – user2998504

+0

您是否知道在任何地方都可以使用javax.sound。*包的一些体面的文档作为“官方教程”,我发现它相当冗长和混乱。 – user2998504

+0

我注意到它会运行良好如果我同时打开一个Jframe。 – user2998504