Python中的频率分析

时间:2012-01-31 15:46:01

标签: python numpy fft analysis blender

我正在尝试使用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 Game Environment实现它(因此导入bge位于顶部),但我很确定我的问题在于AnalyseStream模块。

非常感谢您提供的任何建议。

更新:我不时地得到正确的值,但是在不正确的值(< 10Hz)中很少发现它们。那个和程序运行得非常慢。

2 个答案:

答案 0 :(得分:6)

你好发现用于实时分析的最大计算FFT变得有点慢。

如果您不使用复杂的波形来查找频率,您可以使用任何基于时域的方法,例如过零,性能会更好。

在去年,我做了一个简单的函数来通过零交叉计算频率。

#Eng Eder de Souza 01/12/2011
#ederwander
from matplotlib.mlab import find
import pyaudio
import numpy as np
import math


chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 20


def Pitch(signal):
    signal = np.fromstring(signal, 'Int16');
    crossing = [math.copysign(1.0, s) for s in signal]
    index = find(np.diff(crossing));
    f0=round(len(index) *RATE /(2*np.prod(len(signal))))
    return f0;


p = pyaudio.PyAudio()

stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
output = True,
frames_per_buffer = chunk)

for i in range(0, RATE / chunk * RECORD_SECONDS):
    data = stream.read(chunk)
    Frequency=Pitch(data)
    print "%f Frequency" %Frequency

ederwander

答案 1 :(得分:2)

还有函数scipy.signal.lombscargle计算Lomb-Scargle周期图,自v0.10.0起可用。即使对于不均匀采样的信号,该方法也应该有效。似乎必须减去数据的平均值才能使此方法正常工作,尽管文档中没有提到。 更多信息可以在scipy参考指南中找到: http://docs.scipy.org/doc/scipy/reference/tutorial/signal.html#lomb-scargle-periodograms-spectral-lombscargle