簡體   English   中英

在沒有臨時文件的情況下將音頻流轉換為Java中的WAV字節數組

[英]Convert audio stream to WAV byte array in Java without temp file

給定一個調用的InputStream in其中包含壓縮格式的音頻數據(如MP3或OGG),我希望創建一個包含輸入數據的WAV轉換的byte數組。 不幸的是,如果您嘗試這樣做,JavaSound會向您發出以下錯誤:

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;

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

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

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

我注意到這個問題很久以前就被問過了。 如果任何新人(使用Java 7及更高版本)找到此線程,請注意通過Files.readAllBytes API有一種更好的新方法。 請參閱: 如何將.wav文件轉換為字節數組?

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

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

如果您准備將為您創建正確標題的類,則該問題很容易解決。 在我的示例示例中,如何讀取wav緩沖區數據中的音頻輸入進入某個緩沖區,之后我創建了標頭並在緩沖區中有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類。

這很簡單......

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文件。

暫無
暫無

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

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