Skip to content

Instantly share code, notes, and snippets.

@SaeedPrez
Created February 3, 2022 17:42
Show Gist options
  • Save SaeedPrez/03c446641e968dbfa2eaeb1c88f3f0de to your computer and use it in GitHub Desktop.
Save SaeedPrez/03c446641e968dbfa2eaeb1c88f3f0de to your computer and use it in GitHub Desktop.
Simple audio visualizer for Unity
using System.Linq;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class AudioVisualizer : MonoBehaviour
{
[SerializeField] private float barWidth = 0.1f;
[SerializeField] private float updateDelay = 0.04f;
[SerializeField] private Color[] barColors;
[SerializeField] private float barMultiplier = 2f;
private float[] spectrumData = new float[64];
private float[] spectrumGrouped = new float[5];
private float updateTime = 0f;
void Update()
{
// Wait for next update time
if (updateTime > Time.time)
return;
// Get spectrum data
AudioListener.GetSpectrumData(spectrumData, 0, FFTWindow.BlackmanHarris);
// Set next update time
updateTime = Time.time + updateDelay;
}
private void OnDrawGizmos()
{
// Group the bars so we only have 5 bars
// You can play around with these to your liking
spectrumGrouped[0] = spectrumData[0..1].Sum();
spectrumGrouped[1] = spectrumData[2..5].Sum();
spectrumGrouped[2] = spectrumData[6..13].Sum();
spectrumGrouped[3] = spectrumData[14..30].Sum();
spectrumGrouped[4] = spectrumData[31..63].Sum();
// Draw a gizmo for each bar
for (int i = 0; i < spectrumGrouped.Length; i++)
{
// Calculate and clamp bar height
var barHeight = Mathf.Clamp(spectrumGrouped[i] * barMultiplier, 0.001f, 1f);
// Set bar color
Gizmos.color = barColors[i];
// Draw bar
Gizmos.DrawCube(
new Vector3(i * barWidth, barHeight / 2f, 0f), // Center
new Vector3(barWidth, barHeight, barWidth)); // Size
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment