Getting different bytes from the same audio file

89 Views Asked by At

I am trying to convert the audio file to a standard format and read the bytes.

First thing I do is:

static void main(String [] args)
{
    File file = new File("/path/to/my/file.mp3");
    AudioInputStream source = AudioSystem.getAudioInputStream(file);
    AudioFormat sourceFormat = source.getFormat();

    AudioFormat convertFormat = new AudioFormat(
                AudioFormat.Encoding.PCM_SIGNED,
                sourceFormat.getSampleRate(),
                16,
                sourceFormat.getChannels(),
                sourceFormat.getChannels() * 2,
                sourceFormat.getSampleRate(),
                false);
    AudioInputStream convert1AIS = AudioSystem.getAudioInputStream(convertFormat, source);

    AudioFormat targetFormat = new AudioFormat(
            44100,
            8,
            1,
            true,
            true);

    AudioInputStream target = AudioSystem.getAudioInputStream(targetFormat, convert1AIS);

    byte[] buffer = new byte[4096];


    //Here come strange things
    target.read(buffer,0, buffer.length);


}

Every time I start the program, the buffer contains different bytes, i.e first 10 bytes, which I see in the debugger are never the same. What is wrong?

I have added the following libraries: jl1.0.1.jar, jtransform-2.4.jar, mp3spi1.9.5.jar, tritonus_remaining-0.3.6.jar, tritonus_share.jar

OS. Ubuntu 14.04

java version "1.8.0_111" Java(TM) SE Runtime Environment (build 1.8.0_111-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode)

1

There are 1 best solutions below

6
On

The core thing is: it is not guaranteed that a call to read will always read the exact same amount of bytes from your input.

To the contrary, that read method returns the number of bytes read back to you. So you always need a loop that keeps reading until all expected bytes were really read!

Edit: given your comments: you are doing an audio conversion here; so my guess is: this process is simply not deterministic. In other words: the real input bytes for that MP3 file would always be the same; but your code runs transformations on that; and as said; those transformations are non-deterministic; and therefore creating slightly different results for each run.