簡體   English   中英

Java Sounds適用於JRE6但不適用於JRE7

[英]Java Sounds work on JRE6 but not JRE7

我一直在試圖解決這個問題,我已經在我一直在研究的計算器中使用這種方法:

public void error_sound() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
    AudioInputStream AIS = AudioSystem.getAudioInputStream(calculator.class.getResourceAsStream("/resources/Error.wav"));
    AudioFormat format = AIS.getFormat();
    SourceDataLine playbackLine = AudioSystem.getSourceDataLine(format);
    playbackLine.open(format);
    playbackLine.start();
    int bytesRead = 0;
    byte[] buffer = new byte[128000];
    while (bytesRead != -1) {
        bytesRead = AIS.read(buffer, 0, buffer.length);
        if (bytesRead >= 0)
            playbackLine.write(buffer, 0, bytesRead);
        }
    playbackLine.drain();
    playbackLine.close();
}

此代碼適用於JRE6,但不適用於JRE7。 如果有人可以建議一種方法在JRE7上完成上述工作,我會永遠感激嗎?

看來Sun在JRE 1.7中刪除了“Java Sound Audio Engine”,這是我唯一可以理解的內容嗎?

“看起來Sun在JRE 1.7中放棄了”Java Sound Audio Engine“,這是我唯一可以理解的東西?”

不, 會被很多人,包括我的注意。 您的評論表明有資源的輸入流中尋找一個問題。 這可能是由不同的音頻系統或getAudioStream()的不同實現引起的。

您可以嘗試將資源流包裝到BufferedInputStream中:

InputStream raw = calculator.class.getResourceAsStream("/resources/Error.wav");
InputStream bis = new BufferedInputStream(raw, 20000);
AudioInputStream ais = AudioSystem.getAudioInputStream(bis);

(這是基於BufferedInputStream支持標記/重置的想法)

真的應該加入一些適當的錯誤處理代碼(檢查資源等有正確和錯誤日志/報告)。 如果能夠清楚地報告問題,那么從長遠來看確實很有幫助。

編輯:重新閱讀你的問題描述,它清楚你是從eclipse運行代碼,在另一台計算機上運行jar文件。 問題是你的代碼不能應付后者。 將它包裝到BufferedInputStream中應該修復它(你可能需要增加緩沖區大小)。

編輯2:嘗試重復聲音:

public void error_sound() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
    AudioInputStream AIS = ...
    AudioFormat format = ...
    SourceDataLine playbackLine = ...
    playbackLine.open(format);
    playbackLine.start();

    int repeats = 5;
    while (true) {
       // playloop
       int bytesRead = 0;
       byte[] buffer = new byte[128000];
       while (bytesRead != -1) {
           bytesRead = AIS.read(buffer, 0, buffer.length);
           if (bytesRead >= 0)
                playbackLine.write(buffer, 0, bytesRead);
       }
       --repeats;
       if (repeats <= 0) {
           // done, stop playing
           break;
       } else {
           // repeat one more time, reset audio stream
           AIS = ...
       }
   }
   playbackLine.drain();
   playbackLine.close();
}

唯一復雜的是你需要音頻流來獲取格式,並且你還需要在每次循環迭代中重新創建它以從頭開始讀取它。 其他一切都保持不變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM