Bel
Bel

Reputation: 312

arrays java:90 (ArrayIndexOutOfBoundsException)

Then i do this code:

 private int[] getAmplitude(byte[] fft) {
        int[] amplitude = new int[fft.length/2-2] ;
        for (int i = 2; i <= fft.length/2-2;i+= 2) {
            for(int j=0;j<= fft.length/2-2;j++){
            amplitude[j]=(fft[i] * fft[i] + fft[i + 1] * fft[i + 1]);}
        }
        return amplitude;

i got this:

java.lang.ArrayIndexOutOfBoundsException
    at com.astroplayerbeta.gui.eq.EqVisualizerCaptureAudio.getAmplitude(EqVisualizerCaptureAudio.java:90)
    at com.astroplayerbeta.gui.eq.EqVisualizerCaptureAudio.onFftDataCapture(EqVisualizerCaptureAudio.java:67)
    at android.media.audiofx.Visualizer$NativeEventHandler.handleMessage(Visualizer.java:484)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3835)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
    at dalvik.system.NativeStart.main(Native Method)

That is my trouble?

fft[] array got 1024 length.

Upvotes: 0

Views: 354

Answers (1)

Oren
Oren

Reputation: 4252

Lets say fft.length/2-2 is 3. then amplitude is an array of size 3.

Now you say

for(int j=0;j<= fft.length/2-2;j++){
    amplitude[j]=(fft[i] * fft[i] + fft[i + 1] * fft[i + 1]);
}

If I were to write that in english it would be: for j = 0 to 3 put somthing in amplitude[j]. so you are putting 4 values into amplitude, which is an array of size 3. and so you are getting an ArrayIndexOutOfBoundsException. Change the lines to

for(int j=0;j< fft.length/2-2;j++){
    amplitude[j]=(fft[i] * fft[i] + fft[i + 1] * fft[i + 1]);
}

(the <= changed to <) and you should be set.

Note that you also have a similar problem with fft and its for-loop.

Upvotes: 1

Related Questions