转换音频流为WAV字节数组在Java中没有临时文件 [英] Convert audio stream to WAV byte array in Java without temp file

查看:1163
本文介绍了转换音频流为WAV字节数组在Java中没有临时文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个的InputStream 名为(其中包含一个COM pressed格式的音频数据,诸如MP3或OGG),我想创建一个字节包含输入数据的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?

推荐答案

的问题是,最AudioFileWriters需要知道文件的大小提前如果写入的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.

但是,你可以尝试使用AudioOutputStream架构从Tritonus插件(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

这篇关于转换音频流为WAV字节数组在Java中没有临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆