【发布时间】:2012-02-23 08:13:26
【问题描述】:
我正在尝试使用 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 模块中。
您能提供的任何建议将不胜感激。
更新:我时不时地得到正确的值,但在不正确的值(
【问题讨论】:
-
1920 的采样率看起来很可疑。更典型的音频采样率为 8000 或 44100。您使用哪种声音进行正确性测试?如果不是来自正弦波发生器,您听到的音高和频率峰值可能会有很大不同。
标签: python numpy fft analysis blender