class Topaz::TempoCalculator

Calculate tempo given timestamps

Constants

THRESHOLD

Attributes

tempo[R]
timestamps[R]

Public Class Methods

new() click to toggle source
# File lib/topaz/tempo_calculator.rb, line 10
def initialize
  @tempo = nil
  @timestamps = []
end

Public Instance Methods

calculate() click to toggle source

Analyze the tempo based on the threshold @return [Float, nil] The tempo as a float, or nil if there’s not enough data to calculate it

# File lib/topaz/tempo_calculator.rb, line 17
def calculate
  tempo = nil
  if @timestamps.count >= 2
    limit_timestamps
    deltas = get_deltas
    sum = deltas.inject(&:+)
    average = sum.to_f / deltas.count
    bpm = ppq24_millis_to_bpm(average)
    @tempo = bpm
  end
end

Private Instance Methods

get_deltas() click to toggle source

Get the delta values between the timestamps @return [Array<Float>]

# File lib/topaz/tempo_calculator.rb, line 42
def get_deltas
  @timestamps.each_cons(2).map { |a,b| b - a }
end
limit_timestamps() click to toggle source

Limit the timestamp list to within the threshold @return [Array<Time>, nil]

# File lib/topaz/tempo_calculator.rb, line 33
def limit_timestamps
  if @timestamps.count > THRESHOLD
    @timestamps.slice!(THRESHOLD - @timestamps.count, THRESHOLD)
    @timstamps
  end
end
ppq24_millis_to_bpm(ppq24) click to toggle source

Convert the raw tick intervals to beats-per-minute (BPM) @param [Float] ppq24 @return [Float]

# File lib/topaz/tempo_calculator.rb, line 49
def ppq24_millis_to_bpm(ppq24)
  quarter_note = ppq24.to_f * 24.to_f
  60 / quarter_note
end