I have implemented FFT/DFT that I intend to use for frequency analysis of an audio file recorded from a fan. Here’s the input I get when using scipy’s fft. As opposed to this, here’s the output from my implementation.
So far, my code looks like this:
from scipy.fft import fft
import soundfile as sf
import numpy as np
import matplotlib.pyplot as plt
from pydub import AudioSegment
def dft(filename):
audio_seg = AudioSegment.from_file(filename)
data = audio_seg.set_channels(1).get_array_of_samples()
N = len(data)
n = np.arange(0, N)
k = np.linspace(1, 1000, 1500)
X = np.zeros(len(k))
for i in range (0, len(k)):
base_sinusoid = np.exp(-2j * np.pi * k[i] * n / N)
dot_product = np.dot(data, base_sinusoid)
X[i] = np.abs(dot_product)
energy_sum = 0
for i in range(0, len(X)):
energy_sum += X[i] ** 2
present_frequencies = []
for i in range(0, len(X)):
if (((X[i] ** 2) * 100 / energy_sum) >= 1):
present_frequencies.append(k[i])
print("The following frequencies are present: ", present_frequencies)
plt.figure(1)
plt.title("Frequency analysis")
plt.xlabel("Frequency")
plt.ylabel("Magnitude")
plt.plot(k, X)
plt.show()
and then I simply call the function:
dft(<absolute path>)
Apart from the image, I also output
the frequencies whose energy represents more than 1% of the entire signal’s energy.
The audio file is recorded from a fan with 10 blades, and around 200 Hz is the expected fundamental frequency. The frequency content is supposed to go up to 1000 Hz.
What I suspect may be the problem is an incorrect frequency resolution. Since I generate my own sinusoids, I may just be selecting the wrong frequencies. In my opinion, instead of generating 1500 frequencies (line 8), I should be generating N frequencies, however that takes a very long time to execute. So, I’ve mostly tried changing the maximum frequency, and the width of the frequency bins, but to no avail.
I should also note that I’ve used this function before on audio files where I say a vowel for 3 seconds, and it generated a correct output. The only difference there was in line 8, where I set the maximum frequency to be 20000.
Thank you for your time and insight!
sudoMeerkat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.