在没有临时文件的情况下将音频流转换为Java中的WAV字节数组

给定一个调用的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需要事先知道文件大小。 因为您无法提供此function,所以始终会失败。 不幸的是,默认的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文件。