2008-10-13 37 views
7

給定一個名爲inInputStream,其中包含壓縮格式(如MP3或OGG)的音頻數據,我希望創建一個包含輸入的WAV轉換的byte數組數據。不幸的是,如果你嘗試這樣做,JavaSound給了你以下錯誤:將音頻流轉換爲Java格式的WAV字節數組,無臨時文件

java.io.IOException: stream length not specified 

我設法得到它通過寫WAV到一個臨時文件,然後在回讀,工作,如下圖所示:

AudioInputStream source = AudioSystem.getAudioInputStream(new BufferedInputStream(in, 1024)); 
AudioInputStream pcm = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, source); 
AudioInputStream ulaw = AudioSystem.getAudioInputStream(AudioFormat.Encoding.ULAW, pcm); 
File tempFile = File.createTempFile("wav", "tmp"); 
AudioSystem.write(ulaw, AudioFileFormat.Type.WAVE, tempFile); 
// The fileToByteArray() method reads the file 
// into a byte array; omitted for brevity 
byte[] bytes = fileToByteArray(tempFile); 
tempFile.delete(); 
return bytes; 

這顯然不太理想。有沒有更好的辦法?

回答

6

問題是,如果寫入OutputStream,大多數AudioFileWriters需要提前知道文件大小。因爲你不能提供這個,它總是失敗。不幸的是,默認的Java聲音API實現沒有任何選擇。

但是你可以嘗試使用AudioOutputStream架構從Tritonus插件(Tritonus是一個開源實現的Java API聲音的):http://tritonus.org/plugins.html

+1

我得試試看。在我嘗試之前可能會有一點點,所以目前我無法接受答案。不過,我會鼓勵它。 – 2008-10-21 22:43:00

-2

這是非常簡單的...

File f = new File(exportFileName+".tmp"); 
File f2 = new File(exportFileName); 
long l = f.length(); 
FileInputStream fi = new FileInputStream(f); 
AudioInputStream ai = new AudioInputStream(fi,mainFormat,l/4); 
AudioSystem.write(ai, Type.WAVE, f2); 
fi.close(); 
f.delete(); 

的.tmp文件是一個RAW音頻文件,結果是帶有標題的WAV文件。

+1

問題問是否可以完成*沒有臨時文件。 – 2012-07-02 15:21:16

1

我注意到這是很久以前問過的。如果有任何新人(使用Java 7及以上版本)發現此線程,請注意,通過Files.readAllBytes API執行此操作有更好的新方法。請參閱: How to convert .wav file into byte array?

1

太遲了,我知道,但我需要這個,所以這是我的兩分錢的話題。

public void UploadFiles(String fileName, byte[] bFile) 
{ 
    String uploadedFileLocation = "c:\\"; 

    AudioInputStream source; 
    AudioInputStream pcm; 
    InputStream b_in = new ByteArrayInputStream(bFile); 
    source = AudioSystem.getAudioInputStream(new BufferedInputStream(b_in)); 
    pcm = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, source); 
    File newFile = new File(uploadedFileLocation + fileName); 
    AudioSystem.write(pcm, Type.WAVE, newFile); 

    source.close(); 
    pcm.close(); 
} 
-1

這個問題很容易解決,如果你準備的類會爲你創建正確的標題。在我的示例Example how to read audio input in wav buffer數據進入一些緩衝區,之後我創建標題並在緩衝區中有wav文件。無需額外的庫。只需複製示例中的代碼即可。

示例如何使用類緩存陣列中創建正確的標題:

public void run() {  
    try {  
     writer = new NewWaveWriter(44100); 

     byte[]buffer = new byte[256]; 
     int res = 0; 
     while((res = m_audioInputStream.read(buffer)) > 0) { 
      writer.write(buffer, 0, res); 
     } 
    } catch (IOException e) { 
     System.out.println("Error: " + e.getMessage()); 
    }  
}  

public byte[]getResult() throws IOException { 
    return writer.getByteBuffer(); 
} 

和類NewWaveWriter你可以在我的鏈接找到。

相關問題