Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Audio visualizer in unity with blend shapes
/*Please do support www.bitshiftprogrammer.com by joining the facebook page : fb.com/BitshiftProgrammer
Legal Stuff:
This code is free to use no restrictions but attribution would be appreciated.
Any damage caused either partly or completly due to usage of this stuff is not my responsibility*/
using UnityEngine;
[RequireComponent(typeof(SkinnedMeshRenderer))]
public class AudioVisualizer : MonoBehaviour
{
[Range(1.0f,4500.0f)]
public float multiplier;
public int minRange = 0;
public int maxRange = 64;
private SkinnedMeshRenderer skinnedMeshRenderer;
private float prevAvg = 0.0f;
void Start ()
{
skinnedMeshRenderer = GetComponent<SkinnedMeshRenderer> ();
}
void Update ()
{
float[] spectrum = new float[64];
AudioListener.GetSpectrumData(spectrum, 0, FFTWindow.BlackmanHarris);
if (maxRange < minRange)
maxRange = minRange + 1;
minRange = Mathf.Clamp(minRange, 0, 63);
maxRange = Mathf.Clamp(maxRange, 0, 63);
float avg = 0;
for (int i = minRange; i < maxRange; i++)
avg += Mathf.Abs(spectrum[i]);
avg = avg / (float)Mathf.Abs(maxRange - minRange);
if (avg - prevAvg > 0.0012f)
avg = prevAvg + 0.0012f;
else if (avg - prevAvg < -0.0012f)
avg = prevAvg - 0.0012f;
skinnedMeshRenderer.SetBlendShapeWeight(0, avg*multiplier);
prevAvg = avg;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.