Python中的频率分析

11

我正在尝试使用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 Game环境一起使用(因此在顶部导入了bge),但我相当确定我的问题存在于AnalyseStream模块中。
如果您能提供任何建议,将不胜感激。
更新:我偶尔会得到正确的值,但它们很少在错误的值(<10Hz)中找到。而且程序运行非常缓慢。

1
1920的采样率看起来有些可疑。更典型的音频采样率是8000或44100。你用什么样的声音进行正确性测试?如果不是来自正弦波发生器,你听到的音高和频率峰值可能会非常不同。 - hotpaw2
2个回答

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


2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接