Save jPDFNotes’ Raw Audio To WAV File Using Java
Posted by tech on
September 18, 2009
jPDFNotes’ Sound Annotation object produces raw audio through its getContent() method and an AudioFormat object via its getFormat() method. To convert raw audio to any of its supported audio format, you would have to use Java Sound classes for this to happen.
Below is the method to convert the raw audio to a WAV file.
public static void saveWavAsFile(byte[] byte_array, AudioFormat audioFormat, String file) { try { long length = (long)(byte_array.length / audioFormat.getFrameSize()); ByteArrayInputStream bais = new ByteArrayInputStream(byte_array); AudioInputStream audioInputStreamTemp = new AudioInputStream(bais, audioFormat, length); File fileOut = new File(file); AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE; if (AudioSystem.isFileTypeSupported(fileType, audioInputStreamTemp)) { AudioSystem.write(audioInputStreamTemp, fileType, fileOut); } } catch(Exception e) { } }
To use it, do this (assuming “sound” is your Sound Annotation object).
saveWavAsFile(sound.getContent(), sound.getFormat(), "./test.wav");
If you want the output returned as an array of bytes (in case you want to convert the WAV to some other format like MP3), you can change the AudioSystem.write() method to use an OutputStream object as the last parameter instead of a File object.
public static ByteArrayOutputStream saveWavByteArrayOutputStream(byte[] byte_array, AudioFormat audioFormat) { ByteArrayOutputStream baos = null; try { long length = (long)(byte_array.length / audioFormat.getFrameSize()); ByteArrayInputStream bais = new ByteArrayInputStream(byte_array); AudioInputStream audioInputStreamTemp = new AudioInputStream(bais, audioFormat, length); AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE; if (AudioSystem.isFileTypeSupported(fileType, audioInputStreamTemp)) { baos = new ByteArrayOutputStream(); AudioSystem.write(audioInputStreamTemp, fileType, baos); } } catch(Exception e) { } return baos; }
Since my method returns a ByteArrayOutputStream object, you can call the method toByteArray() to have it return in byte[].
Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.







