0
votes

I am struggling to understand the 24 bit mono PCM audio format data and read this data in Java.

I understand and can read RIFF header but cannot figure out how to read 24 bit PCM samples. I need to read PCM samples one by one.

1
The Java Sound APIs should be able to read this, the javasound tag info has links to lots of examples. - greg-449

1 Answers

1
votes

Assuming little-endian encoding, this should get you started:

// constant holding the minimum value of a signed 24bit sample: -2^22.
private static final int MIN_VALUE_24BIT = -2 << 22;

// constant holding the maximum value a signed 24bit sample can have, 2^(22-1).
private static final int MAX_VALUE_24BIT = -MIN_VALUE_24BIT-1;

[...]
// open your AudioInputStream using AudioSystem and read values into a buffer buf
[...]

final byte[] buf = ... ;      // your audio byte buffer
final int bytesPerSample = 3; // because 24 / 8 = 3

// read one sample:
int sample = 0;
for (int byteIndex = 0; byteIndex < bytesPerSample; byteIndex++) {
    final int aByte = buf[byteIndex] & 0xff;
    sample += aByte << 8 * (byteIndex);
}

// now handle the sign / valid range
final int threeByteSample = sample > MAX_VALUE_24BIT
    ? sample + MIN_VALUE_24BIT + MIN_VALUE_24BIT
    : sample;

// do something with your threeByteSample / read the next sample

See jipes AudioSignalSource for more general handling of PCM decoding.