I have the following two function that loads any given WAV file into a byte array and gets the format (i.e. AudioFormat
) of a given WAV file respectively:
private byte[] getAudioData(String wavPath) throws IOException, UnsupportedAudioFileException {
byte[] data = null;
ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream(); // The stream that collects all the audio byte data
File audioFile = new File(wavPath);
AudioInputStream audioIS = AudioSystem.getAudioInputStream(audioFile);
/*
* Reads all the bytes from the audio files.
* It can only read a certain length of bytes at a time, hence the intermediate buffer.
*/
byte[] intermediateBuffer = new byte[4096];
int numberOfBytesRead;
while((numberOfBytesRead = audioIS.read(intermediateBuffer, 0, intermediateBuffer.length)) != -1){
byteArrayOS.write(intermediateBuffer, 0, numberOfBytesRead);
}
audioIS.close();
byteArrayOS.close();
data = byteArrayOS.toByteArray(); // Gets total number of bytes in the audio file.
return data;
}
private AudioFormat getAudioFormat(String wavPath) throws UnsupportedAudioFileException, IOException {
File audioFile = new File(wavPath);
AudioInputStream audioIS = AudioSystem.getAudioInputStream(audioFile);
AudioFormat audioFormat = audioIS.getFormat();
audioIS.close();
return audioFormat;
}
Now, I have the following saving function that 1.) loads the format of the WAV file, 2.) loads the data from the WAV file, and finally 3.) saves everything to a new file.
public void saveAudio(String wavPath, File destination) throws IOException, UnsupportedAudioFileException {
AudioFormat format = getAudioFormat(wavPath);
byte[] audioData = getAudioData(wavPath);
ByteArrayInputStream byteArrayIS = new ByteArrayInputStream(audioData);
AudioInputStream audioIS = new AudioInputStream(byteArrayIS, format, audioData.length);
AudioSystem.write(audioIS, AudioFileFormat.Type.WAVE, destination);
}
If the original data is 16-bit sample rate, PCM-signed audio, everything works just fine. However, if the audio is 32-bit sample rate, PCM-float audio, the resulting saved audio file produces a lot of crackling noise with very distorted audio.
Why does this happen? Do any of the functions I reply on only allow 16-bit sample rate audio?