2014-02-26 159 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