tags:

views:

94

answers:

1

I need your help. I'd like to use the following code since I'm developing an audio tool (for .wav files only) whose main feature is displaying a signal waveform. Big Endian as well as Little endian are elements I can't help dealing with. Am I right in thinking that the following code tackles the problem in a way that: - if the audio file sample size is 16 bit or 8 bit, and Big endian or Little endian it rearranges the samples using the audioData array?

If my reasoning is correct , does the rearrangement is always from big endian to little endian ?

Is the computer architecture taken into account? (I mean if my computer uses Little endian, what happens?)

Thank you

int[] audioData = null;

if (format.getSampleSizeInBits() == 16) {
                int nlengthInSamples = audioBytes.size() / 2;
                audioData = new int[nlengthInSamples];
                // se Big Endian
                if (format.isBigEndian()) {
                    for (int i = 0; i < nlengthInSamples; i++) {
                        // MSB calculation - Most Significant Bit
                        int MSB = (int) audioBytes.get(2 * i);
                        // LSB calculation  - Least Significant Bit
                        int LSB = (int) audioBytes.get(2 * i + 1);
                        // (MSB << 8) MSB shift to the left by 8 position
                        // (255 & LSB) LSB masking so that LSB is <255 or =0
                        // putting both together
                        audioData[i] = MSB << 8 | (255 & LSB);
                    }
                } else {
                    for (int i = 0; i < nlengthInSamples; i++) {
                        int LSB = (int) audioBytes.get(2 * i);
                        int MSB = (int) audioBytes.get(2 * i + 1);
                        audioData[i] = MSB << 8 | (255 & LSB);
                    }
                }
+1  A: 

Everything in Java is Big Endian, so you don't need to worry about that. What you have appears correct (obviously, test it to be sure) but I would recommend using the following pattern to avoid code replication down the road.

int nlengthInSamples = audioBytes.size() / 2;
audioData = new int[nlengthInSamples];

// default BigEndian
int MSB = (int) audioBytes.get(2 * i);
int LSB = (int) audioBytes.get(2 * i + 1);

// swap for Little Endian
if(!format.isBigEndian()) {
    int temp = MSB;
    MSB = LSB;
    LSB = temp;
}

audioData[i] = MSB << 8 | (255 & LSB);
glowcoder
You still need a loop.
Alexander Pogrebnyak