Burnner

Untitled

Mar 27th, 2015
4,910
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.70 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. public class AudioProcessor : MonoBehaviour
  6. {
  7.  
  8.  
  9.  
  10.     private AudioSource source;
  11.  
  12.     private long lastT, nowT, diff, entries, sum;
  13.  
  14.     private List<AudioCallbacks> callbacks;
  15.  
  16.     public int bufferSize = 1024; // fft size
  17.     private int samplingRate = 44100; // fft sampling frequency
  18.  
  19.     /* log-frequency averaging controls */
  20.     private int nBand = 12; // number of bands
  21.  
  22.     public float gThresh = 0.1f; // sensitivity
  23.  
  24.     int blipDelayLen = 16;
  25.     int[] blipDelay;
  26.  
  27.     private int sinceLast = 0; // counter to suppress double-beats
  28.  
  29.     private float framePeriod;
  30.  
  31.     /* storage space */
  32.     private int colmax = 120;
  33.     float[] onsets;
  34.     float[] scorefun;
  35.     float[] dobeat;
  36.     int now = 0; // time index for circular buffer within above
  37.  
  38.     float[] spec; // the spectrum of the previous step
  39.  
  40.     /* Autocorrelation structure */
  41.     int maxlag = 100; // (in frames) largest lag to track
  42.     float decay = 0.997f; // smoothing constant for running average
  43.     Autoco auco;
  44.  
  45.     private float alph; // trade-off constant between tempo deviation penalty and onset strength
  46.  
  47.     //////////////////////////////////
  48.     private long getCurrentTimeMillis()
  49.     {
  50.         long milliseconds = System.DateTime.Now.Ticks / System.TimeSpan.TicksPerMillisecond;
  51.         return milliseconds;
  52.     }
  53.  
  54.     private void initArrays()
  55.     {
  56.         blipDelay = new int[blipDelayLen];
  57.         onsets = new float[colmax];
  58.         scorefun = new float[colmax];
  59.         dobeat = new float[colmax];
  60.         alph = 100 * gThresh;
  61.     }
  62.  
  63.  
  64.     void Awake()
  65.     {
  66.         callbacks = new List<AudioCallbacks>();
  67.     }
  68.     // Use this for initialization
  69.     void Start()
  70.     {
  71.  
  72.         initArrays();
  73.  
  74.         samplingRate = 44100;
  75.  
  76.         framePeriod = (float)bufferSize / (float)samplingRate;
  77.  
  78.         //initialize record of previous spectrum
  79.         spec = new float[nBand];
  80.         for (int i = 0; i < nBand; ++i) spec[i] = 100.0f;
  81.  
  82.         auco = new Autoco(maxlag, decay, framePeriod, getBandWidth());
  83.  
  84.         lastT = getCurrentTimeMillis();
  85.         source = GetComponent<AudioSource>();
  86.     }
  87.  
  88.     public void tapTempo()
  89.     {
  90.         nowT = getCurrentTimeMillis();
  91.         diff = nowT - lastT;
  92.         lastT = nowT;
  93.         sum = sum + diff;
  94.         entries++;
  95.  
  96.         int average = (int)(sum / entries);
  97.  
  98.         Debug.Log("average = " + average);
  99.     }
  100.  
  101.     double[] toDoubleArray(float[] arr)
  102.     {
  103.         if (arr == null) return null;
  104.         int n = arr.Length;
  105.         double[] ret = new double[n];
  106.         for (int i = 0; i < n; i++)
  107.         {
  108.             ret[i] = (float)arr[i];
  109.         }
  110.         return ret;
  111.     }
  112.  
  113.     // Update is called once per frame
  114.     void Update()
  115.     {
  116.        
  117.         if (source.isPlaying)
  118.         {
  119.             float[] spectrum = new float[bufferSize];
  120.             GetComponent<AudioSource>().GetSpectrumData(spectrum, 0, FFTWindow.BlackmanHarris);
  121.             float[] averages = computeAverages(spectrum);
  122.  
  123.             if (callbacks != null)
  124.             {
  125.                 foreach (AudioCallbacks callback in callbacks)
  126.                 {
  127.                     callback.onSpectrum(averages);
  128.                 }
  129.             }
  130.  
  131.             /* calculate the value of the onset function in this frame */
  132.             float onset = 0;
  133.             for (int i = 0; i < nBand; i++)
  134.             {
  135.                 float specVal = (float)System.Math.Max(-100.0f, 20.0f * (float)System.Math.Log10(averages[i]) + 160); // dB value of this band
  136.                 specVal *= 0.025f;
  137.                 float dbInc = specVal - spec[i]; // dB increment since last frame
  138.                 spec[i] = specVal; // record this frome to use next time around
  139.                 onset += dbInc; // onset function is the sum of dB increments
  140.             }
  141.  
  142.             onsets[now] = onset;
  143.  
  144.             /* update autocorrelator and find peak lag = current tempo */
  145.             auco.newVal(onset);
  146.             // record largest value in (weighted) autocorrelation as it will be the tempo
  147.             float aMax = 0.0f;
  148.             int tempopd = 0;
  149.             float[] acVals = new float[maxlag];
  150.             for (int i = 0; i < maxlag; ++i)
  151.             {
  152.                 float acVal = (float)System.Math.Sqrt(auco.autoco(i));
  153.                 if (acVal > aMax)
  154.                 {
  155.                     aMax = acVal;
  156.                     tempopd = i;
  157.                 }
  158.                 // store in array backwards, so it displays right-to-left, in line with traces
  159.                 acVals[maxlag - 1 - i] = acVal;
  160.             }
  161.  
  162.             /* calculate DP-ish function to update the best-score function */
  163.             float smax = -999999;
  164.             int smaxix = 0;
  165.             // weight can be varied dynamically with the mouse
  166.             alph = 100 * gThresh;
  167.             // consider all possible preceding beat times from 0.5 to 2.0 x current tempo period
  168.             for (int i = tempopd / 2; i < System.Math.Min(colmax, 2 * tempopd); ++i)
  169.             {
  170.                 // objective function - this beat's cost + score to last beat + transition penalty
  171.                 float score = onset + scorefun[(now - i + colmax) % colmax] - alph * (float)System.Math.Pow(System.Math.Log((float)i / (float)tempopd), 2);
  172.                 // keep track of the best-scoring predecesor
  173.                 if (score > smax)
  174.                 {
  175.                     smax = score;
  176.                     smaxix = i;
  177.                 }
  178.             }
  179.  
  180.             scorefun[now] = smax;
  181.             // keep the smallest value in the score fn window as zero, by subtracing the min val
  182.             float smin = scorefun[0];
  183.             for (int i = 0; i < colmax; ++i)
  184.                 if (scorefun[i] < smin)
  185.                     smin = scorefun[i];
  186.             for (int i = 0; i < colmax; ++i)
  187.                 scorefun[i] -= smin;
  188.  
  189.             /* find the largest value in the score fn window, to decide if we emit a blip */
  190.             smax = scorefun[0];
  191.             smaxix = 0;
  192.             for (int i = 0; i < colmax; ++i)
  193.             {
  194.                 if (scorefun[i] > smax)
  195.                 {
  196.                     smax = scorefun[i];
  197.                     smaxix = i;
  198.                 }
  199.             }
  200.  
  201.             // dobeat array records where we actally place beats
  202.             dobeat[now] = 0;  // default is no beat this frame
  203.             ++sinceLast;
  204.             // if current value is largest in the array, probably means we're on a beat
  205.             if (smaxix == now)
  206.             {
  207.                 //tapTempo();
  208.                 // make sure the most recent beat wasn't too recently
  209.                 if (sinceLast > tempopd / 4)
  210.                 {
  211.                     if (callbacks != null)
  212.                     {
  213.                         foreach (AudioCallbacks callback in callbacks)
  214.                         {
  215.                             callback.onOnbeatDetected();
  216.                         }
  217.                     }
  218.                     blipDelay[0] = 1;
  219.                     // record that we did actually mark a beat this frame
  220.                     dobeat[now] = 1;
  221.                     // reset counter of frames since last beat
  222.                     sinceLast = 0;
  223.                 }
  224.             }
  225.  
  226.             /* update column index (for ring buffer) */
  227.             if (++now == colmax) now = 0;
  228.  
  229.             //Debug.Log(System.Math.Round(60 / (tempopd * framePeriod)) + " bpm");
  230.             //Debug.Log(System.Math.Round(auco.avgBpm()) + " bpm");
  231.         }
  232.     }
  233.  
  234.     public void changeCameraColor()
  235.     {
  236.         //Debug.Log("camera");
  237.         float r = Random.Range(0f, 1f);
  238.         float g = Random.Range(0f, 1f);
  239.         float b = Random.Range(0f, 1f);
  240.  
  241.         //Debug.Log(r + "," + g + "," + b);
  242.         Color color = new Color(r, g, b);
  243.  
  244.         GetComponent<Camera>().clearFlags = CameraClearFlags.Color;
  245.         Camera.main.backgroundColor = color;
  246.  
  247.         //camera.backgroundColor = color;
  248.     }
  249.  
  250.     public float getBandWidth()
  251.     {
  252.         return (2f / (float)bufferSize) * (samplingRate / 2f);
  253.     }
  254.  
  255.     public int freqToIndex(int freq)
  256.     {
  257.         // special case: freq is lower than the bandwidth of spectrum[0]
  258.         if (freq < getBandWidth() / 2) return 0;
  259.         // special case: freq is within the bandwidth of spectrum[512]
  260.         if (freq > samplingRate / 2 - getBandWidth() / 2) return (bufferSize / 2);
  261.         // all other cases
  262.         float fraction = (float)freq / (float)samplingRate;
  263.         int i = (int)System.Math.Round(bufferSize * fraction);
  264.         //Debug.Log("frequency: " + freq + ", index: " + i);
  265.         return i;
  266.     }
  267.  
  268.     public float[] computeAverages(float[] data)
  269.     {
  270.         float[] averages = new float[12];
  271.         for (int i = 0; i < 12; i++)
  272.         {
  273.             float avg = 0;
  274.             int lowFreq;
  275.             if (i == 0)
  276.                 lowFreq = 0;
  277.             else
  278.                 lowFreq = (int)((samplingRate / 2) / (float)System.Math.Pow(2, 12 - i));
  279.             int hiFreq = (int)((samplingRate / 2) / (float)System.Math.Pow(2, 11 - i));
  280.             int lowBound = freqToIndex(lowFreq);
  281.             int hiBound = freqToIndex(hiFreq);
  282.             for (int j = lowBound; j <= hiBound; j++)
  283.             {
  284.                 //Debug.Log("lowbound: " + lowBound + ", highbound: " + hiBound);
  285.                 avg += data[j];
  286.             }
  287.             // line has been changed since discussion in the comments
  288.             // avg /= (hiBound - lowBound);
  289.             avg /= (hiBound - lowBound + 1);
  290.             averages[i] = avg;
  291.         }
  292.  
  293.         return averages;
  294.     }
  295.  
  296.     float map(float s, float a1, float a2, float b1, float b2)
  297.     {
  298.         return b1 + (s - a1) * (b2 - b1) / (a2 - a1);
  299.     }
  300.  
  301.     public float constrain(float value, float inclusiveMinimum, float inlusiveMaximum)
  302.     {
  303.         if (value >= inclusiveMinimum)
  304.         {
  305.             if (value <= inlusiveMaximum)
  306.             {
  307.                 return value;
  308.             }
  309.  
  310.             return inlusiveMaximum;
  311.         }
  312.  
  313.         return inclusiveMinimum;
  314.     }
  315.  
  316.     public void addAudioCallback(AudioCallbacks callback)
  317.     {
  318.         this.callbacks.Add(callback);
  319.         //Debug.Log(callback);
  320.     }
  321.  
  322.     public void removeAudioCallback(AudioCallbacks callback)
  323.     {
  324.         this.callbacks.Remove(callback);
  325.     }
  326.  
  327.     public interface AudioCallbacks
  328.     {
  329.         void onOnbeatDetected();
  330.         void onSpectrum(float[] spectrum);
  331.     }
  332.  
  333.     // class to compute an array of online autocorrelators
  334.     private class Autoco
  335.     {
  336.         private int del_length;
  337.         private float decay;
  338.         private float[] delays;
  339.         private float[] outputs;
  340.         private int indx;
  341.  
  342.         private float[] bpms;
  343.         private float[] rweight;
  344.         private float wmidbpm = 120f;
  345.         private float woctavewidth;
  346.  
  347.         public Autoco(int len, float alpha, float framePeriod, float bandwidth)
  348.         {
  349.             woctavewidth = bandwidth;
  350.             decay = alpha;
  351.             del_length = len;
  352.             delays = new float[del_length];
  353.             outputs = new float[del_length];
  354.             indx = 0;
  355.  
  356.             // calculate a log-lag gaussian weighting function, to prefer tempi around 120 bpm
  357.             bpms = new float[del_length];
  358.             rweight = new float[del_length];
  359.             for (int i = 0; i < del_length; ++i)
  360.             {
  361.                 bpms[i] = 60.0f / (framePeriod * (float)i);
  362.                 //Debug.Log(bpms[i]);
  363.                 // weighting is Gaussian on log-BPM axis, centered at wmidbpm, SD = woctavewidth octaves
  364.                 rweight[i] = (float)System.Math.Exp(-0.5f * System.Math.Pow(System.Math.Log(bpms[i] / wmidbpm) / System.Math.Log(2.0f) / woctavewidth, 2.0f));
  365.             }
  366.         }
  367.  
  368.         public void newVal(float val)
  369.         {
  370.  
  371.             delays[indx] = val;
  372.  
  373.             // update running autocorrelator values
  374.             for (int i = 0; i < del_length; ++i)
  375.             {
  376.                 int delix = (indx - i + del_length) % del_length;
  377.                 outputs[i] += (1 - decay) * (delays[indx] * delays[delix] - outputs[i]);
  378.             }
  379.  
  380.             if (++indx == del_length) indx = 0;
  381.         }
  382.  
  383.         // read back the current autocorrelator value at a particular lag
  384.         public float autoco(int del)
  385.         {
  386.             float blah = rweight[del] * outputs[del];
  387.             return blah;
  388.         }
  389.  
  390.         public float avgBpm()
  391.         {
  392.             float sum = 0;
  393.             for (int i = 0; i < bpms.Length; ++i)
  394.             {
  395.                 sum += bpms[i];
  396.             }
  397.             return sum / del_length;
  398.         }
  399.     }
  400. }
Advertisement
Add Comment
Please, Sign In to add comment