Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2014
2,699
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Spectrum : MonoBehaviour {
  5. public AudioSource song;
  6. public GameObject cube;
  7.  
  8. float[] historyBuffer = new float[43];
  9.  
  10. // Use this for initialization
  11. void Start () {
  12. }
  13.  
  14. // Update is called once per frame
  15. void Update () {
  16.  
  17. //compute instant sound energy
  18. float[] channelRight = song.audio.GetOutputData (1024,1);
  19. float[] channelLeft = song.audio.GetOutputData(1024,2);
  20.  
  21. float e = sumStereo (channelLeft, channelRight);
  22.  
  23. //compute local average sound evergy
  24. float E = sumLocalEnergy ()/historyBuffer.Length; // E being the average local sound energy
  25.  
  26. //calculate variance
  27. float sumV = 0;
  28. for (int i = 0; i< 43; i++)
  29. sumV += (historyBuffer[i]-E)*(historyBuffer[i]-E);
  30.  
  31. float V = sumV/historyBuffer.Length;
  32. float constant = (float)((-0.0025714 * V) + 1.5142857);
  33.  
  34. float[] shiftingHistoryBuffer = new float[historyBuffer.Length]; // make a new array and copy all the values to it
  35.  
  36. for (int i = 0; i<(historyBuffer.Length-1); i++) { // now we shift the array one slot to the right
  37. shiftingHistoryBuffer[i+1] = historyBuffer[i]; // and fill the empty slot with the new instant sound energy
  38. }
  39.  
  40. shiftingHistoryBuffer [0] = e;
  41.  
  42. for (int i = 0; i<historyBuffer.Length; i++) {
  43. historyBuffer[i] = shiftingHistoryBuffer[i]; //then we return the values to the original array
  44. }
  45.  
  46. if (e > (constant * E)) { // now we check if we have a beat
  47. cube.GetComponent<SpriteRenderer> ().color = Color.red;
  48. } else {
  49. cube.GetComponent<SpriteRenderer> ().color = Color.yellow;
  50. }
  51.  
  52. Debug.Log ("Avg local: " + E);
  53. Debug.Log ("Instant: " + e);
  54. Debug.Log ("History Buffer: " + historybuffer());
  55. Debug.Log ("sum Variance: " + sumV);
  56. Debug.Log ("Variance: " + V);
  57. Debug.Log ("Constant: " + constant);
  58. Debug.Log ("--------");
  59. }
  60.  
  61. float sumStereo(float[] channel1, float[] channel2) {
  62. float e = 0;
  63. for (int i = 0; i<channel1.Length; i++) {
  64. e += ((channel1[i]*channel1[i]) + (channel2[i]*channel2[i]));
  65. }
  66.  
  67. return e;
  68. }
  69.  
  70. float sumLocalEnergy() {
  71. float E = 0;
  72.  
  73. for (int i = 0; i<historyBuffer.Length; i++) {
  74. E += historyBuffer[i]*historyBuffer[i];
  75. }
  76.  
  77. return E;
  78. }
  79.  
  80. string historybuffer() {
  81. string s = "";
  82. for (int i = 0; i<historyBuffer.Length; i++) {
  83. s += (historyBuffer[i] + ",");
  84. }
  85. return s;
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement