0

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.

greg-449
  • 109,219
  • 232
  • 102
  • 145
user1744147
  • 1,099
  • 13
  • 30
  • The Java Sound APIs should be able to read this, the [javasound tag info](https://stackoverflow.com/tags/javasound/info) has links to lots of examples. – greg-449 May 09 '19 at 06:45

1 Answers1

1

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.

Hendrik
  • 5,085
  • 24
  • 56
  • 1
    This is good. Big point is the comment: "// Open your AudioInputStream..." When set to the proper Format, there is no need to decode or parse the RIFF header. The only data you will deal with is the PCM. – Phil Freihofner May 09 '19 at 16:53