package dsp import ( "math/cmplx" "github.com/maddyblue/go-dsp/fft" "periph.io/x/conn/v3/physic" "git.maze.io/go/bragi/internal/audio" ) // Analyzer for audio signals. type Analyzer struct { signal audio.Complex128 } type FrequencySpectrum struct { // Store the frequency spectrum values Spectrum []float64 // Store the frequencies used Frequencies []float64 } // FrequencySpectrum calculates the frequency spectrum of the signal. func (s *Analyzer) FrequencySpectrum(samples audio.Slice, rate physic.Frequency) (*FrequencySpectrum, error) { // Copy the samples to our complex buffer. length := samples.Len() if len(s.signal) < length { s.signal = make(audio.Complex128, length) } else { s.signal = s.signal[:length] } samples.CopyTo(s.signal) // Apply the FFT on the signal to get the frequency components ffft := fft.FFT(s.signal) // Compute the two sided spectrum var spectrum2 []float64 flength := float64(length) for i := range ffft { // Get the absolute value since the fft is a complex value with both real and imaginary parts spectrum2 = append(spectrum2, cmplx.Abs(ffft[i])/flength) } // Look at the one sided spectrum spectrum1 := spectrum2[0 : len(spectrum2)/2] for i := range spectrum1 { spectrum1[i] = spectrum1[i] * 2 } var ( frequencies []float64 spectrumLength = float64(len(spectrum2)) scale = rate.Period().Seconds() / spectrumLength ) for i := range spectrum1 { // Calculate which frequencies the spectrum contains frequencies = append(frequencies, float64(i)*scale) } return &FrequencySpectrum{ Spectrum: spectrum1, Frequencies: frequencies, }, nil }