Python中的频率分析

11 投票
2 回答
14246 浏览
提问于 2025-04-17 12:02

我正在尝试用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游戏环境中使用(所以顶部有import bge),但我觉得我的问题主要出在AnalyseStream模块上。

如果你能提供一些建议,我会非常感激。

更新:我偶尔能得到正确的值,但大多数时候都是错误的值(小于10Hz)。而且程序运行得非常慢。

2 个回答

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
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

撰写回答