PCM 16bit recording byte vs short

Viewed 705

I am trying to record audio on Android. I have found different examples, but one thing I didn't understand.

Some people write shorts, other bytes.

Here is an example of converting short to bytes.

   private byte[] short2byte(short[] sData) {
        int shortArrsize = sData.length;
        byte[] bytes = new byte[shortArrsize * 2];
        for (int i = 0; i < shortArrsize; i++) {
            bytes[i * 2] = (byte) (sData[i] & 0x00FF);
            bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
            sData[i] = 0;
        }
        return bytes;

    }

What is the purpose of doing that ? Why not to write shorts directly to file, as far as we are using PCM 16bit.

Please explain this matter from the audio perspective.

Thanks

1 Answers

In Java you can't "write shorts directly" as there is no API that takes a short array and writes that to a file. You can only write byte arrays to a binary file. The chief problem is endianness (LSB first or MSB first): there's no standard endian.

Therefore you have two choices:

  • Use a little-endian ShortBuffer which is backed by a ByteBuffer to encode the short array
  • Just encode the shorts as bytes yourself, which is what the code you posted does.
Related