diff --git a/shazam/filter.go b/shazam/filter.go index 32419eb..d8b3db5 100644 --- a/shazam/filter.go +++ b/shazam/filter.go @@ -4,34 +4,33 @@ import ( "math" ) -// LowPassFilter implements a simple first-order low-pass filter +// LowPassFilter is a first-order low-pass filter using H(p) = 1 / (1 + pRC) type LowPassFilter struct { alpha float64 // Filter coefficient yPrev float64 // Previous output value } -// NewLowPassFilter creates a new LowPassFilter with the specified cutoff frequency and sample rate +// NewLowPassFilter creates a new low-pass filter func NewLowPassFilter(cutoffFrequency, sampleRate float64) *LowPassFilter { - // Calculate filter coefficient (alpha) based on cutoff frequency and sample rate - alpha := 1.0 - math.Exp(-2.0*math.Pi*cutoffFrequency/sampleRate) - + rc := 1.0 / (2 * math.Pi * cutoffFrequency) + dt := 1.0 / sampleRate + alpha := dt / (rc + dt) return &LowPassFilter{ alpha: alpha, yPrev: 0, } } -// Filter filters the input signal using the low-pass filter and returns the filtered output +// Filter processes the input signal through the low-pass filter func (lpf *LowPassFilter) Filter(input []float64) []float64 { filtered := make([]float64, len(input)) - for i, x := range input { - // Update filter output using the single-pole low-pass filter equation - output := lpf.alpha*x + (1-lpf.alpha)*lpf.yPrev - lpf.yPrev = output - - filtered[i] = output + if i == 0 { + filtered[i] = x * lpf.alpha + } else { + filtered[i] = lpf.alpha*x + (1-lpf.alpha)*lpf.yPrev + } + lpf.yPrev = filtered[i] } - return filtered }