在没有临时文件的 Java 中将音频流转换为 WAV 字节数组 [英] Convert audio stream to WAV byte array in Java without temp file
问题描述
给定一个名为 in
的 InputStream
,其中包含压缩格式(例如 MP3 或 OGG)的音频数据,我希望创建一个 byte
包含输入数据的 WAV 转换的数组.不幸的是,如果您尝试这样做,JavaSound 会给您以下错误:
Given an InputStream
called in
which contains audio data in a compressed format (such as MP3 or OGG), I wish to create a byte
array containing a WAV conversion of the input data. Unfortunately, if you try to do this, JavaSound hands you the following error:
java.io.IOException: stream length not specified
我设法通过将 wav 写入临时文件,然后将其读回来使其工作,如下所示:
I managed to get it to work by writing the wav to a temporary file, then reading it back in, as shown below:
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;
这显然不太理想.有没有更好的办法?
This is obviously less desirable. Is there a better way?
推荐答案
问题是大多数 AudioFileWriter 在写入 OutputStream 时需要提前知道文件大小.因为你不能提供这个,它总是失败.不幸的是,默认的 Java 声音 API 实现没有任何替代方案.
The problem is that the most AudioFileWriters need to know the file size in advance if writing to an OutputStream. Because you can't provide this, it always fails. Unfortunatly, the default Java sound API implementation doesn't have any alternatives.
但是您可以尝试使用 Tritonus 插件中的 AudioOutputStream 架构(Tritonus 是 Java 声音 API 的开源实现):http://tritonus.org/plugins.html
But you can try using the AudioOutputStream architecture from the Tritonus plugins (Tritonus is an open source implementation of the Java sound API): http://tritonus.org/plugins.html
这篇关于在没有临时文件的 Java 中将音频流转换为 WAV 字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!