我试图使用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()
该代码是从this question中分离出来的,后者处理波形文件的傅里叶分析。它在当前的模块化结构中,因为我是在Blender游戏环境中实现它的(因此在顶部是import bge),但是我很确定我的问题在AnalyseStream模块中。
如果您能提供任何建议,我们将不胜感激。
更新:我时不时地得到正确的值,但在不正确的值中很少发现这些值(<;10Hz)。这个程序运行得很慢。