0

I have an existing logic to convert a byte array to alaw (wav) file. We have changed our backend. After this, the conversation starts producing file bad content (noise instead of proper voice)

It works well if I save the byte array to an mp3 file through FileUtils.writeByteArrayToFile. But the conversion from byte array to wav does not work.

Can you please help with what is going wrong?

/**
 * Adds a file header for a wave file encoded with a-law.
 *
 * @param audioBytes the raw audio bytes
 * @return the bytes prepended by a wave file header.
 */
public byte[] rawToALaw(byte[] audioBytes) {
    System.out.println("Adding wave header to audio");
    System.out.println("rawToALaw (audioBytes.length="+audioBytes.length+")");

    float sampleRate = 8000.0f;
    boolean bigEndian = false;
    int bits = 8;
    int channels = 1;
    AudioFormat format = new AudioFormat(AudioFormat.Encoding.ALAW, sampleRate, bits, channels,
            (int) (channels*bits/8), sampleRate, bigEndian);

    return rawToWave(audioBytes, bits, format);
}

public byte[] rawToWave(byte[] audioBytes, int bits, AudioFormat format) {
    long frames = calculateFrames(audioBytes.length, bits);
    ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);
    AudioInputStream audioInputStream = new AudioInputStream(bais, format, frames);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, out);
    } catch (IOException e) {
        System.out.println("Failed to add wave file header to audio.");
    } finally {
        try {
            audioInputStream.close();
        } catch (IOException e) {
            System.out.println("Failed to close audio input stream when trying to add the wave file header.");
        }
    }
    return out.toByteArray();
}

public long calculateFrames(int size, int bits) {
    return (long) (size*8/bits);
}

This is how I cam calling it.

byte [] converted = this.rawToALaw(rawBytes);
File file = new File("c:\\workx\\ttstest.wav");
FileUtils.writeByteArrayToFile(file, converted);
Abdul Waheed
  • 63
  • 1
  • 10

0 Answers0