Python中的频率分析

2024-05-19 15:52:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: andtheimportwhichdataratenpfind
2条回答

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

Hello find the maximum computing the FFT for real-time analysis变得有点慢。

如果你不想用复杂的波形来寻找频率,你可以使用任何基于时域的方法,比如过零点法,这样性能会更好。

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

#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

爱德华

相关问题 更多 >