我有以下两个函数将任何给定的 WAV 文件加载到字节数组中并AudioFormat
分别获取给定 WAV 文件的格式(即):
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;
}
现在,我有以下保存功能:1.)加载 WAV 文件的格式,2.)从 WAV 文件中加载数据,最后3.)将所有内容保存到新文件中。
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);
}
如果原始数据是 16 位采样率、PCM 签名的音频,那么一切正常。但是,如果音频是 32 位采样率、PCM-float 音频,则保存的音频文件会产生大量噼啪声和非常失真的音频。
为什么会这样?我回复的任何功能是否只允许 16 位采样率音频?