Search code examples
javajavasoundpcmwave

how to convert byte array to integer?


I have a byte array which contains pure sound data. I want to convert it to integer. bit per sample is 16. frame rate is 44100. but how to convert it into an integer?


Solution

  • Just to clearify: You have a byte[] that contains pairs of byte's to form an integer? So like this: {int1B1, int1B2, int2B1, int2B2, int3B1, int3B2, ...}?

    If so, you can assemble them to integers like this:

    int[] audio = new int[byteArray.length/2];
    for (int i = 0; i < byteArray.length/2; i++) { // read in the samples
      int lsb = byteArray[i * 2 + 0] & 0xFF; // "least significant byte"
      int msb = byteArray[i * 2 + 1] & 0xFF; // "most significant byte"
      audio[i] = (msb << 8) + lsb;
    }
    

    Of course you can optimize that loop to a single line loop, but I prefer it that way for better readability. Also, depending on the endianness of the data, you can switch ub1 and ub2.