In Unity, I have a script that is meant to take audio input from the mic, and get its spectrum data.
When I attach this to a game object and hit 'play', the script correctly gets the loudness of the mic, but gives an error when trying to get the spectrum data. Specifically, it gives this error:
AudioSource.GetSpectrumData failed; Length of the sample buffer must be a power of two between 64 and 8192.
What can I do to resolve this?
My script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioAnalyzer : MonoBehaviour
{
string micName;
AudioSource micAudioSource;
public float loudness;
int sampleWindow = 512;
public float[] spectrum = new float[512];
void Start()
{
micName = Microphone.devices[0];
micAudioSource = GetComponent<AudioSource>();
micAudioSource.clip = Microphone.Start(micName, true, 10, AudioSettings.outputSampleRate);
}
void Update()
{
loudness = GetLoudness();
SetSpectrum();
}
float GetLoudness()
{
int clipPosition = Microphone.GetPosition(micName);
int startPosition = clipPosition - sampleWindow;
if (startPosition < 0) {
startPosition = 0;
}
float[] waveData = new float[sampleWindow];
micAudioSource.clip.GetData(waveData, startPosition);
float totalLoudness = 0f;
for (int i = 0; i < sampleWindow; i++) {
totalLoudness += Mathf.Abs(waveData[i]);
}
float avgLoudness = totalLoudness / sampleWindow;
return avgLoudness;
}
void SetSpectrum() {
micAudioSource.GetSpectrumData(spectrum, 0, FFTWindow.Blackman);
}
}