Converts an audio stream to a wav byte array in Java without a temporary file
Given a called InputStream containing audio data in compressed format (such as MP3 or Ogg), I want to create a byte array of wav conversion containing input data Unfortunately, if you try this, javasound will send you the following error:
java.io.IOException: stream length not specified
I try to make wav work by writing it to a temporary file and then reading it back, as follows:
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 not ideal Is there a better way?
Solution
The problem is that if OutputStream is written, most audiofilewriters need to know the file size in advance Because you cannot provide this function, it will always fail Unfortunately, there is no alternative to the default Java sound API implementation
However, you can try to use the audiooutputstream architecture in the tritonus plug-in (tritonus is an open source implementation of the Java sound API): http://tritonus.org/plugins.html