I am trying to create an audio visualizer in the Unity game engine using C#.
I am also using the FMOD plugin which has functions for retrieving the audio spectrum of a playing sound (aka the volume of a sound across a range of frequencies).
FMOD returns this data as a struct containing a jagged array, with the first array being the audio channel (0 = left, 1 = right), and the second array being the volumes for each frequency range, being a float value between 0 and 1.
I need to copy the values in these arrays into my own arrays, for the purposes of altering and displaying the data. I am currently using a for-loop to iterate through the array and assign the values from the left and right channels to new arrays, as well as another array that finds the average volume:
private int SAMPLE_SIZE = 512;
private float[] spectrumLeft;
private float[] spectrumRight;
public float[] spectrumTotal;
void Start () {
spectrumLeft = new float[SAMPLE_SIZE];
spectrumRight = new float[SAMPLE_SIZE];
spectrumTotal = new float[SAMPLE_SIZE];
}
void Update () {
System.IntPtr data;
uint length;
result = spectrumFilter.getParameterData ((int)FMOD.DSP_FFT.SPECTRUMDATA, out data, out length);
FMOD.DSP_PARAMETER_FFT spectrumBuffer = new FMOD.DSP_PARAMETER_FFT ();
spectrumBuffer = (FMOD.DSP_PARAMETER_FFT) Marshal.PtrToStructure(data,typeof (FMOD.DSP_PARAMETER_FFT));
for (int i = 0; i < SAMPLE_SIZE; i++) {
spectrumLeft[i] = spectrumBuffer.spectrum[0][i];
spectrumRight[i] = spectrumBuffer.spectrum[1][i];
spectrumTotal[i] = (spectrumLeft[i] + spectrumRight[i]) / 2f;
}
}
THE PROBLEM: The code running in the for-loop above is incredibly slow (It maxes out my CPU core and causes the program to run slowly, when I comment out the contents of the loop the CPU usage is below 1%).
Since FMOD returns the data as a struct in this format I cannot change how I retrieve the data.
Is there a better/faster way of retrieving values from a struct?
Note that I am relatively new to C# and I may be missing something obvious