Conversion of Audio Format

Vijay Suryawanshi picture Vijay Suryawanshi · May 9, 2012 · Viewed 13.1k times · Source

I am having trouble in converting the audio format of a WAV file.

I am recording sound from my microphone and the sound is recorded in the following format: PCM_SIGNED 44100.0 Hz, 16 bit, mono, 2 bytes/frame

I want to convert the above format to, ULAW 8000.0 Hz, 8 bit, mono, 1 bytes/frame

I am using the following code,

InputStream is = request.getInputStream(); 
            AudioInputStream ais = AudioSystem.getAudioInputStream(is);
            AudioFormat oldFormat = ais.getFormat();
            AudioFormat newFormat = new AudioFormat(AudioFormat.Encoding.ULAW, 8000, 8, 1, 1, 8000, false) ;
AudioInputStream lowResAIS = AudioSystem.getAudioInputStream(newFormat, ais); //Getting the below Exception on this line

And I am getting the following error,

java.lang.IllegalArgumentException: Unsupported conversion: ULAW 8000.0 Hz, 8 bit, mono, 1 bytes/frame, from PCM_SIGNED 44100.0 Hz, 16 bit, mono, 2 bytes/frame, little-endian

Can someone please help me solve this problem!!!

Thanks a ton!!!

Answer

Andrzej Doyle picture Andrzej Doyle · May 9, 2012

Did you take a look at the documentation?

Throws: IllegalArgumentException - if the conversion is not supported #see #getTargetEncodings(AudioFormat)

Not every system will have sufficient codecs installed to transform to the specific format you've asked for. You've assumed yours does, but it's throwing the exception because it can't transform to that format.

You can use getTargetEncodings to check the suitability of a given format programatically, without relying on an exception, and then can take appropriate action if you desired output format isn't available (e.g. fall back to another one, present the user with feedback that this is impossible, etc.).