Writing JavaSound to audio file with stream

I am trying to create a sound filter using the JavaSound API to read and write audio files. Currently my code is structured like this:

        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 the bytearrayoutputstream, but waits until the entire file has been processed before writing to disk. Ideally, I would like each sample to disk to be processed as it is processed. I have tried several combinations of stream constructs but cannot find a way to do this since AudioSystem.write () accepts an input stream. Any ideas?

+1


source to share


3 answers


kasperjj's answer is correct. You may be working with WAV files. See this for composing a wave file. Please note that the size of the entire WAV file is encoded in its header.



I don't know if this applies in your case, but for handling WAV samples as you described, you can use a "normal" Java silent stream. For example, you can use FileOutputStream to write them to a temporary file, and after processing, you can convert the temporary file to a valid WAV file.

+2


source


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



However, there are many audio formats that can be transferred easily. Many of them have open source libraries for java, so if you want to add an external library it shouldn't be that hard.

+1


source


The problem can be resolved if you reimplement the AudioSystem.write method. It does not work with Stream and WAVE format. You have to read data from AudioInputStream, cache it in a byte array, process the array, and write to a wave file. I would recommend you check out the classes from the example: How to write audio to a byte array

0


source







All Articles