Below is the code of the process of receiving the microphone sound in real time and performing the FFT. For noise cancellation, it is blocked in IFFT process. Do you have any resources or methods to help me?
Also, is there a library that performs inverse FFT inside python?
#complile by python3 new.py
import pyaudio
import numpy as np
import wave
import time
from pydub import AudioSegment
from pydub.playback import play
RATE = 44100
CHUNK = 512
WIDTH = 2
#use a blackman window
window = np.blackman(CHUNK)
#load audio stream
p = pyaudio.PyAudio()
player = p.open(format=pyaudio.paInt16,
channels=1,
rate=RATE,
output=True,
frames_per_buffer=CHUNK)
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
#do this for 10 seconds
for i in range(int(20*RATE/CHUNK)):
sound = stream.read(CHUNK)
player.write(np.fromstring(sound,dtype=np.int16),CHUNK)
#unpack the data and times by hamming window
indata = np.array(wave.struct.unpack("%dh"%(len(sound)/WIDTH),\
sound))*window
#take the fft and square each value
fftData = abs(np.fft.rfft(indata))*2
#find the maxium
which = fftData[1:].argmax() + 1
#use quadratic interpolation around the max
if which != len(fftData)-1:
y0, y1, y2 = np.log(fftData[which-1:which+2:])
x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
#find the frequency and output it
thefreq = (which + x1) * RATE / CHUNK
print("The freq is %f Hz." % (thefreq))
else:
thefreq = which * RATE / CHUNK
print("The freq is %f Hz." % (thefreq))
stream.stop_stream()
stream.close()
p.terminate()