Skip to content

Instantly share code, notes, and snippets.

@rje
Created April 29, 2014 18:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rje/11408219 to your computer and use it in GitHub Desktop.
Save rje/11408219 to your computer and use it in GitHub Desktop.
audio spectrum code
using UnityEngine;
using System.Collections;
/// <summary>
/// A class for taking spectrum data & calculating the volume of various frequency bands.
///
/// Notes:
/// This doesn't do any smoothing, so wherever you leverage these values you'll probably want to do something.
/// In my project I immediately jump to any higher value, and then have it decay over time at a fixed rate.
/// </summary>
public class SpectrumAnalyzer : MonoBehaviour {
// The audio source to grab spectrum data from. Probably your music track
public AudioSource Source;
// Audio channel to use, I think 0 is left channel and 1 is right channel?
public int Channel = 0;
// Number of samples to take, a high value here is usually a good idea. I use 1024 by default
public int NumSamples = 1024;
// Each vector in this array describes the frequency bands you want to track, in my project I use:
// 20 - 31.5
// 31.5 - 63
// 63 - 125
// 125 - 250
// 250 - 800
// 800 - 2000
// 2000 - 3500
// 3500 - 6000
// 6000 - 12000
// 12000 - 23000
public Vector2[] Bands;
// The volume of each band - should be between 0 & 1. Updated each frame.
public float[] BandVolumes;
// The average volume of all bands
public float AverageVolume;
float _fMax;
float[] _samples;
public int NumBands
{
get
{
return Bands.Length;
}
}
void Start()
{
_samples = new float[NumSamples];
BandVolumes = new float[NumBands];
_fMax = AudioSettings.outputSampleRate / 2.0f;
}
void Update()
{
Source.GetSpectrumData(_samples, 0, FFTWindow.BlackmanHarris);
AverageVolume = 0;
for (var i = 0; i < NumBands; i++)
{
var band = Bands[i];
var n1 = Mathf.FloorToInt(band.x * NumSamples / _fMax);
var n2 = Mathf.FloorToInt(band.y * NumSamples / _fMax);
float sum = 0;
for (var f = n1; f <= n2; f++)
{
sum += _samples[f];
}
BandVolumes[i] = sum;
AverageVolume += sum;
}
AverageVolume /= BandVolumes.Length;
}
}
@DomDomHaas
Copy link

Awesome!
Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment