2016-06-21 74 views
2

我想打開一個.wav文件,並使用剪輯播放它。但是,當我打電話myClip.open(...),線程凍結,永遠不會恢復。沒有錯誤被拋出。下面是我的一個簡單的代碼版本:Java的clip.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.start()之後,包含clip.open(...)的線程也會永久運行。

+0

嘗試寫入一個線程。否則,它會阻止你的主線程,感覺像凍結。 – Boola

回答

0
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()生成一個新線程本身。

+0

這確實解決了我的凍結問題,但它也創建了一個永不會結束的新線程。我想這不是問題,對吧? –

+0

我寫了一個方法來避免這種情況。只要你使用clip.start(),它會產生一個新的線程。你的代碼中的實際問題是你只是打開剪輯,但從不開始。所以它等待剪輯開始。 – Boola

+0

我編輯我的帖子,以確定爲什麼不起作用。 –