python频率_Python中的频率分析

这段Python代码旨在从麦克风读取音频流并分析主频率。通过PyAudio库获取音频数据,然后应用Blackman窗函数和快速傅里叶变换(FFT)进行频率分析。然而,结果不稳定,有时返回不准确的低频值,并且运行效率较低。
摘要由CSDN通过智能技术生成

我试图使用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)。这个程序运行得很慢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值