views:

757

answers:

2

I'm attempting to create an audio filter using the JavaSound API to read and write the audio files. Currently my code is structured as follows:

  ByteArrayOutputStream b_out = new ByteArrayOutputStream();

     // Read a frame from the file.
     while (audioInputStream.read(audioBytes) != -1) { 
   //Do stuff here....
      b_out.write(outputvalue);
     } 

     // Hook output stream to output file
     ByteArrayInputStream b_in  = new ByteArrayInputStream(b_out.toByteArray());
     AudioInputStream  ais  = new AudioInputStream(b_in, format, length);
     AudioSystem.write(ais, inFileFormat.getType(), outputFile);

This reads the input file as a stream, processes it and writes it to a bytearrayoutputstream, but it waits until the entire file has been processed before writing to disk. Ideally, I would like it to write each sample to disk as it's processed. I've tried several combinations of stream constructs but can't find a way of doing it as AudioSystem.write() takes an input stream. Any ideas?

+1  A: 

Some audio formats require metadata describing the length of the stream (or the number of chunks) in their header, thus making it impossible to start writing the data before the entire dataset is present. Inorder for the Java sound API to handle all formats with the same API, I suspect they have had to impose this limit on purpose.

There are however many audio formats that can easily be streamed. Many of them have open library implementations for java, so if you are willing to add an external lib it shouldn't be that hard to accomplish.

kasperjj
A: 

kasperjj's answer is right. You are probably working with WAV files. Look at this for the layout of a wave file. Note that the size of the entire WAV file is encoded in its header.

I don't know if this is applicable in your case, but to process WAV samples as you described, you can use a "regular" non-audio Java output stream. You could use a FileOutputStream for example to write them to a temp file, and after processing you can convert the temp file into a valid WAV file.

eljenso