python – How do I get the corresponding note if given the frequency as an integer
I am taking input from the microphone, performing an FTT and then getting the frequency value corresponding to the greatest y value (amplitude) of the wav file:
import scipy.io.wavfile as wavfile
import scipy
import scipy.fftpack as fftpk
import numpy as np
import wave
import pyaudio
from matplotlib import pyplot as plt
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "voice.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
input_data = wavfile.read(WAVE_OUTPUT_FILENAME)
audio = input_data[1]
s_rate, signal = wavfile.read(WAVE_OUTPUT_FILENAME)
FFT = abs(fftpk.fft(signal))
freqs = fftpk.fftfreq(len(FFT), (1.0/s_rate))
plt.plot(freqs[range(len(FFT)//2)] ,FFT[range(len(FFT)//2)])
threshold = 5000
def find_x(val, xdata, ydata):
x = np.where(ydata == val)
return int(xdata[x])
ydata = FFT[range(len(FFT)//2)]
xdata = freqs[range(len(FFT)//2)]
print(find_x(max(ydata),xdata,ydata))
plt.xlabel("Frequency")
plt.ylabel("Amplitude")
plt.plot(audio)
plt.show()
After receiving the frequency value, I am struggling to convert the frequency into an actual note and return that as a string. It would be appreciated if the community could help me.
Read more here: Source link