Audio.GetSpectrumData() returns NaN

This is driving me nuts and I’m not sure if it’s just a windows 8.1 bug or something, but audio.GetSpectrumData() sometimes returns NaN, and sometimes works with the exact same code. I am so confused.

using UnityEngine;
using System.Collections;

public class AudioSpectrumExample : MonoBehaviour {
	void Update() {
		float[] spectrum = new float[256];
		audio.GetSpectrumData( spectrum, 0, FFTWindow.Hamming);
		Debug.Log (spectrum [54]);
		int i = 1;
		while (i < 255) {
			Debug.DrawLine(new Vector3(i - 1, spectrum *+ 10, 0), new Vector3(i, spectrum[i + 1] + 10, 0), Color.red);*

_ Debug.DrawLine(new Vector3(i - 1, Mathf.Log(spectrum[i - 1]) + 10, 2), new Vector3(i, Mathf.Log(spectrum*) + 10, 2), Color.cyan);_
_ Debug.DrawLine(new Vector3(Mathf.Log(i - 1), spectrum[i - 1] - 10, 1), new Vector3(Mathf.Log(i), spectrum - 10, 1), Color.green);
Debug.DrawLine(new Vector3(Mathf.Log(i - 1), Mathf.Log(spectrum[i - 1]), 3), new Vector3(Mathf.Log(i), Mathf.Log(spectrum), 3), Color.yellow);
i++;
}
}
}*

This line: Debug.Log (spectrum [54), shows me the NaN.
NaN
UnityEngine.Debug:Log(Object)
AudioSpectrumExample:Update() (at Assets/Scripts/MusicVisualizer/AudioSpectrumExample.cs:8)
Thanks for any help!! (And yes I do have an audio source attached to the same game object that’s running that script.)_

Hey bud, you need to add an audio source component to your GameObject holding this script.

You must then supply that AudioSource with an AudioClip (wav,mp3, ogg file).

These are why your above script(taken from Unity docs) is not working, I just copied your script and added the AudioSource compoent to the object with script and imported a quick track…all working fine.
Check you console, when you have done the above and see the Spectrum data recorded in there at runtime.

Image showing it working


Take care bud
Gruffy