- Home /
Question by
ForgeStudios · Jan 28, 2016 at 05:54 AM ·
c#audioprogramminggetspectrumdata
AudioSource.GetSpectrumData Failure
I am currently working on making an audio visualizer in unity, all has been going well, but then all of a sudden, I stopped receiving spectrum data from my script. I had a project like this in the past and the same thing happened to me while I was experimenting with subdividing my sampling ranges. Does anyone know why this happens? The script is attached if you want to try it, you just need to have an audio source and listener on the scene. All audio data should be processed to the barData float array, but it remains at all 0's.
using UnityEngine;
using System.Collections;
public class Visual1 : MonoBehaviour {
public int samplesCount;
public float[] barData;
public float limit;
float[] samples;
int count;
float diff, curValues;
AudioSource audio;
void Start(){
audio = GetComponent<AudioSource>();
samples = new float[samplesCount];
}
void FixedUpdate(){
count = 0; diff = 0;
AudioListener.GetSpectrumData(samples, 0, FFTWindow.BlackmanHarris);
for(int i = 0; i < barData.Length; i ++ /*i += 4*/){
barData[i] = sampleAudio(i, i, (int)Mathf.Pow(2, i + 1));
//Audio Subdivisions for adding more bars and more percision
//barData[i + 1] = sampleAudio(i+1, i, (int)(Mathf.Pow(2, i + 1) + (Mathf.Pow(2, i + 1)/4)));
//barData[i + 2] = sampleAudio(i+2, i, (int)(Mathf.Pow(2, i + 1) + (Mathf.Pow(2, i + 1)/2)));
//barData[i + 3] = sampleAudio(i+3, i, (int)(Mathf.Pow(2, i + 1) + (Mathf.Pow(2, i + 1)/2) + (Mathf.Pow(2, i + 1)/4)));
}
}
float sampleAudio(int c, int h, int sampleCount){
//print(h + " - " + c + ": " + sampleCount); //Debugging
float average = 0;
for(int i = 0; i < sampleCount; i ++){
average += samples[count] * (count + 1);
count++;
}
average /= count;
diff = Mathf.Clamp(average * 10 - curValues, 0, limit);
curValues = average * 10; //Prepare to subtract all previous acconted noise
return diff;
}
}
Thank you in advance for any help!
Comment