5
votes

I'm working on an application that processes audio data. I'm using java (I've added MP3SPI, Jlayer, and Tritonus). I'm extracting the audio data from a .wav file to a byte array. The audio data samples I'm working with are 16 bits stereo.

According to what I've read the format for one sample is:

AABBCCDD

where AABB represents left channel and CCDD rigth channel (2 bytes for each channel). I'd need to convert this sample into a double value type. I've reading about data format. Java uses Big endian, .wav files use little endian. I'm a little bit confused. Could you please help me with the conversion process? Thanks you all

4

4 Answers

5
votes

Warning: integers and bytes are signed. Maybe you need to mask the low bytes when packing them together:

for (int i =0; i < length; i += 4) {
    double left = (double)((bytes [i] & 0xff) | (bytes[i + 1] << 8));
    double right = (double)((bytes [i + 2] & 0xff) | (bytes[i + 3] << 8));

    ... your code here ...

}
4
votes

When you use the ByteBuffer (java.nio.ByteBuffer) you can use the method order;

[order]

public final ByteBuffer order(ByteOrder bo)

Modifies this buffer's byte order.

Parameters:
    bo - The new byte order, either BIG_ENDIAN or LITTLE_ENDIAN
Returns:
    This buffer

After this you can get the above mentioned values with;

getChar() getShort() getInt() getFloat() getDouble()

What a great language is Java ;-)

0
votes

Little Endian means that the data is in the form BBAA and DDCC. You would just swap it around.

From the beginning of the frame:

int left = (bytes[i+1] << 8) + bytes[i];
int right = (bytes[i+3] << 8) + bytes[i+2];

where i is your the index of your sample.

0
votes

I would personally look for a library that does the endian swapping for you. Each audio file format has assumptions about the endianness for you and getting this right is tricky for all the bit depths/datatypes wave files support:

  • 8bit - uint8
  • 16bit - int16
  • 24bit - int32
  • 32bit - int32 as float
  • 32bit - float
  • 64bit - double

If you want to support most common types of wave files you'll need endian conversions for all of these datatypes.

I would look at ByteSwapper, which will give you byteswapping for most of the types listed above.

Its too bad Java doesn't have an endianness field in their File IO classes. Being able to simply open a file whos edianness is big or little is a much easier solution to this issue.