I am trying to work with my built in microphone to create some audio reactive objects. When I open my project and hit play the objects react as I would expect. After stopping the project and hitting play again I get no input. I try a few times to no avail and then suddenly after some time has passed it starts reading the mic again for one run.
I have an audio source attached to my main camera where the fft.cs script is also attached
3206440–245318–fft.cs (2.59 KB)
using UnityEngine;
using System.Collections;
using UnityEngine.Audio;
[RequireComponent(typeof(AudioSource))]
public class fft : MonoBehaviour
{
public bool startMicOnStartup = true;
public int numOfSamples = 1200; //Min: 64, Max: 8192
public AudioSource aSource;
public float[] freqData;
public float[] band;
public GameObject[] g;
void Start()
{
freqData = new float[numOfSamples];
aSource = GetComponent<AudioSource>();
aSource.clip = Microphone.Start(null, true, 10, 44100);
aSource.Play();
int n = freqData.Length;
// checks n is a power of 2 in 2's complement format
if ((n&(n - 1)) != 0)
{
Debug.LogError("freqData length " + n + " is not a power of 2!!! Min: 64, Max: 8192.");
return;
}
int k = 0;
for (int j = 0; j < freqData.Length; j++)
{
n = n / 2;
if (n <= 0) break;
k++;
}
band = new float[k + 1];
g = new GameObject[k + 1];
for (int i = 0; i < band.Length; i++)
{
band[i] = 0;
g[i] = GameObject.CreatePrimitive(PrimitiveType.Sphere);
//g[i].renderer.material.SetColor("_Color", Color.cyan);
g[i].transform.position = new Vector3(i, 0, 0);
}
}
void Update() {
aSource.GetSpectrumData(freqData, 0, FFTWindow.Rectangular);
int k = 0;
int crossover = 2;
for (int i = 0; i < freqData.Length; i++)
{
float d = freqData[i];
//Debug.Log("freq data: " + freqData[i] + "\nband[k]: " + band[k]);
float b = band[k];
// find the max as the peak value in that frequency band.
band[k] = (d > b) ? d : b;
if (i > (crossover - 3))
{
k++;
crossover *= 2; // frequency crossover point for each band.
Vector3 tmp = new Vector3(g[k].transform.position.x, band[k] * 32, g[k].transform.position.z);
//Debug.Log(band[k]);
g[k].transform.position = Vector3.Lerp(g[k].transform.position, tmp, .1f);
Color32 color = new Color32((byte)(50 * band[k]), (byte)(10 * band[k]), (byte)(100 * band[k]), 0);
g[k].GetComponent<Renderer>().material.color = Color32.Lerp(g[k].GetComponent<Renderer>().material.color, new Color32(color.r, color.g, color.b, color.a), .1f);
band[k] = 0;
}
}
}
}