beatDetection.py 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. import numpy
  2. class SimpleBeatDetection:
  3. """
  4. Simple beat detection algorithm from
  5. http://archive.gamedev.net/archive/reference/programming/features/beatdetection/index.html
  6. """
  7. def __init__(self, history = 43):
  8. self.local_energy = numpy.zeros(history) # a simple ring buffer
  9. self.local_energy_index = 0 # the index of the oldest element
  10. def detect_beat(self, signal):
  11. samples = signal.astype(numpy.int) # make room for squares
  12. # optimized sum of squares, i.e faster version of (samples**2).sum()
  13. instant_energy = abs(numpy.dot(samples, samples) / float(0xffffffff)) # normalize
  14. local_energy_average = self.local_energy.mean()
  15. local_energy_variance = self.local_energy.var()
  16. #-0.0025714
  17. beat_sensibility = (-20 * local_energy_variance) +2#+ 1.15142857
  18. beat = instant_energy > beat_sensibility * local_energy_average
  19. #print(" 1" if beat else "0 ", instant_energy/ beat_sensibility / local_energy_average, local_energy_variance)
  20. self.local_energy[self.local_energy_index] = instant_energy
  21. self.local_energy_index -= 1
  22. if self.local_energy_index < 0:
  23. self.local_energy_index = len(self.local_energy) - 1
  24. return beat