1

I have no clue why the: float val = spectrum[i]; is yielding an Index Out of Bounds of the Array. Please help...! I am a complete beginner in this game.

public class InputScript : MonoBehaviour{
    void Start()
    {
        float[] spectrum = new float[256];
        AudioSource aud = GetComponent<AudioSource>();
        aud.clip = Microphone.Start(null, true, 10, 44100);
        aud.Play();

        float maxIndex = 0;
        float maxValue = 0.0f;
        for (int i = 0; i <= spectrum.Length; i++)
        {
            float val = spectrum[i];
            if (val > maxValue)
            {
                maxValue = val;
                maxIndex = i;
            }
        }

        var freq = maxIndex * AudioSettings.outputSampleRate / 2 / spectrum.Length;
    }

    void Update()
    {
        float[] spectrum = new float[256];
        AudioListener.GetSpectrumData(spectrum, 0, FFTWindow.Rectangular);
    }
}

I should be able to extract the pitch of the input from a microphone.

Cœur
  • 37,241
  • 25
  • 195
  • 267
subykan
  • 13
  • 2
  • 2
    Possible duplicate of [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – SᴇM May 06 '19 at 10:28
  • Side note: I can't see where you assign values into `spectrum`; according to your current code `float[] spectrum = new float[256];` is an array of `256` **zeroes**: `{0f, 0f, 0f, ..., 0f}` – Dmitry Bychenko May 06 '19 at 10:53

2 Answers2

2

In .net arrays have indexes from 0 to spectrum.Length exclusive:

for (int i = 0; i < spectrum.Length; i++)
Backs
  • 24,430
  • 5
  • 58
  • 85
1

The problem is this:

for (int i = 0; i <= spectrum.Length; i++)
// ----------------^

You're defining an array of 256 floats, which can be accessed like so:

  • 1st element: spectrum[0]
  • 2nd element: spectrum[1]
  • 256th element: spectrum[255]

As your loop is testing to see if i is less than or equal to spectrum.Length, which we know is 256, this has the effect of trying to access an element at spectrum[256], which is out of range.

Change the comparison in the loop to be less than:

for (int i = 0; i < spectrum.Length; i++)

and this will solve your problem.

John H
  • 14,422
  • 4
  • 41
  • 74