Skip to content

Instantly share code, notes, and snippets.

@josephbk117
Last active November 18, 2018 18:58
Show Gist options
  • Save josephbk117/b7fc9582eb7ec6a670cfa744559cf152 to your computer and use it in GitHub Desktop.
Save josephbk117/b7fc9582eb7ec6a670cfa744559cf152 to your computer and use it in GitHub Desktop.
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