nwaldispuehl/java-lame

ArrayIndexOutOfBoundException

Closed this issue · 1 comments

gqb commented

hi, thank you for creating this project .
I'm using it to decode mp3 file ,but I don't kown how to use it.

this is my code but there is error,code is below:

FileChannel channel = f.getChannel();
                    int frameSize = decoder.getFrameSize();
                    int channels = decoder.getChannels();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(frameSize );
                    try {
                        while(decoder.decode(byteBuffer)){
                            channel.write(byteBuffer);
                            byteBuffer.flip();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    byteBuffer.clear();
                    try {
                        f.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }`

The erro is

:FATAL EXCEPTION: Thread-1177
java.lang.ArrayIndexOutOfBoundsException: length=1152; index=1152
at net.sourceforge.lame.lowlevel.LameDecoder.decode(LameDecoder.java:82)
at com.missevan.android.mdiamerge.MainActivity$1$1.run(MainActivity.java:74)`

please help me, how should I allocate the ByteBuffer .

Hi gqb, thank you for your question.

If you look into the LameDecoder#decode method you see that it not only allocates a buffer of size 1152:

final float buffer[][] = new float[2][1152];

but also calculates some variable iread which is used as limit for a iteration:

int iread = this.lame.getAudio().get_audio16(flags, buffer);

In my case the iread equals to 1152 as well.

Inside of the loop the buffer index is bitshifted according to the number of channels:

sampleBuffer.array()[(i << flags.getInNumChannels()) + 0] = (byte)(sample & 255);

For my stereo sample this is equivalent with a multiplication by four. And indeed if I choose a buffer index of 4 * 1152 = 4608 (YMMV) the decoder runs without error, e.g. like this:

String inputFile = "/path/to/input_file.mp3";
LameDecoder decoder = new LameDecoder(inputFile);

ByteBuffer buffer = ByteBuffer.allocate(4608);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

while (decoder.decode(buffer)) {
  byteArrayOutputStream.write(buffer.array());
}

byte[] pcmByteArray = byteArrayOutputStream.toByteArray();

I will add some means to ease the buffer size determination some time.