Class: Topaz::TempoCalculator

Inherits:
Object
  • Object
show all
Defined in:
lib/topaz/tempo_calculator.rb

Overview

Calculate tempo given timestamps

Constant Summary collapse

THRESHOLD =

minimum number of ticks to analyze

6

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTempoCalculator

Returns a new instance of TempoCalculator.



10
11
12
13
# File 'lib/topaz/tempo_calculator.rb', line 10

def initialize
  @tempo = nil
  @timestamps = []
end

Instance Attribute Details

#tempoObject (readonly)

Returns the value of attribute tempo.



8
9
10
# File 'lib/topaz/tempo_calculator.rb', line 8

def tempo
  @tempo
end

#timestampsObject (readonly)

Returns the value of attribute timestamps.



8
9
10
# File 'lib/topaz/tempo_calculator.rb', line 8

def timestamps
  @timestamps
end

Instance Method Details

#find_tempoObject

Analyze the tempo based on the threshold



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/topaz/tempo_calculator.rb', line 16

def find_tempo
  tempo = nil
  diffs = []
  @timestamps.shift while @timestamps.length > THRESHOLD
  @timestamps.each_with_index { |n, i| (diffs << (@timestamps[i+1] - n)) unless @timestamps[i+1].nil? }
  unless diffs.empty?
    avg = (diffs.inject { |a, b| a + b }.to_f / diffs.length.to_f) 
    tempo = ppq24_millis_to_bpm(avg)
  end 
  @tempo = tempo
end