Getting Audiosource info and data in Unity
Category : Full Script , Game Development , Javascript , Unity
Earlier today I stumbled upon a perfect little script for extracting audio data from an audiosource component in unity. It does all the calculation for getting the RMS value, the decibels, and frequency.
This script can easily be applied to make things behave to the music being played in the Audiosource component. Like making an object bounce or move back and forth with the music.
Thanks to Aldonaletto from this Unity Answers post for making this one and explaining it so well. Script below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
var qSamples: int = 1024; // array size var refValue: float = 0.1; // RMS value for 0 dB var threshold = 0.02; // minimum amplitude to extract pitch var rmsValue: float; // sound level - RMS var dbValue: float; // sound level - dB var pitchValue: float; // sound pitch - Hz private var samples: float[]; // audio samples private var spectrum: float[]; // audio spectrum private var fSample: float; function Start () { samples = new float[qSamples]; spectrum = new float[qSamples]; fSample = AudioSettings.outputSampleRate; } function AnalyzeSound(){ audio.GetOutputData(samples, 0); // fill array with samples var i: int; var sum: float = 0; for (i=0; i < qSamples; i++){ sum += samples[i]*samples[i]; // sum squared samples } rmsValue = Mathf.Sqrt(sum/qSamples); // rms = square root of average dbValue = 20*Mathf.Log10(rmsValue/refValue); // calculate dB if (dbValue < -160) dbValue = -160; // clamp it to -160dB min // get sound spectrum audio.GetSpectrumData(spectrum, 0, FFTWindow.BlackmanHarris); var maxV: float = 0; var maxN: int = 0; for (i=0; i < qSamples; i++){ // find max if (spectrum[i] > maxV && spectrum[i] > threshold){ maxV = spectrum[i]; maxN = i; // maxN is the index of max } } var freqN: float = maxN; // pass the index to a float variable if (maxN > 0 && maxN < qSamples-1){ // interpolate index using neighbours var dL = spectrum[maxN-1]/spectrum[maxN]; var dR = spectrum[maxN+1]/spectrum[maxN]; freqN += 0.5*(dR*dR - dL*dL); } pitchValue = freqN*(fSample/2)/qSamples; // convert index to frequency } var display: GUIText; // drag a GUIText here to show results function Update () { if (Input.GetKeyDown("p")){ audio.Play(); } AnalyzeSound(); if (display){ display.text = "RMS: "+rmsValue.ToString("F2")+" ("+dbValue.ToString("F1")+" dB)\n"+"Pitch: "+pitchValue.ToString("F0")+" Hz"; } } |
A greater explanation is at the source.
Latest posts by Justin Fletcher (see all)
- UITableView scroll to new row only when at the end of table. - December 7, 2015
- Unity Shader for a Scanlines Effect - August 16, 2015
- Unity Shader Alpha Blended With Color - August 16, 2015