为什么保存32位采样率,PCM浮点字节[]到wav文件会产生失真/噼啪声?

时间:2017-11-13 02:41:32

标签: java audio wav pcm sample-rate

我有以下两个函数将任何给定的WAV文件加载到字节数组中并分别获取给定WAV文件的格式(即AudioFormat):

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位采样率音频?

0 个答案:

没有答案