我正在尝试使用Python获取实时音频输入的主要频率。目前,我正在尝试使用我的笔记本电脑内置麦克风的音频流进行实验,但是在测试以下代码时,我得到的结果非常差。
# Read from Mic Input and find the freq's
import pyaudio
import numpy as np
import bge
import wave
chunk = 2048
# use a Blackman window
window = np.blackman(chunk)
# open stream
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 1920
p = pyaudio.PyAudio()
myStream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk)
def AnalyseStream(cont):
data = myStream.read(chunk)
# unpack the data and times by the hamming window
indata = np.array(wave.struct.unpack("%dh"%(chunk), data))*window
# Take the fft and square each value
fftData=abs(np.fft.rfft(indata))**2
# find the maximum
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.close()
# p.terminate()
代码是从这个问题中获取的,该问题涉及波形文件的傅里叶分析。它按照当前的模块化结构编写,因为我正将其与Blender Game环境一起使用(因此在顶部导入了bge),但我相当确定我的问题存在于AnalyseStream模块中。如果您能提供任何建议,将不胜感激。
更新:我偶尔会得到正确的值,但它们很少在错误的值(<10Hz)中找到。而且程序运行非常缓慢。