您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python频率检测

Python频率检测

所述aubio库已经包裹SWIG并且因此可以被Python使用。在它们的许多功能中,包括用于音调检测/估计的几种方法包括YIN算法和一些谐波梳状算法。

但是,如果您想要更简单的方法,我前段时间编写了一些用于音高估算的代码,您可以接受也可以保留它。它不会像使用aubio中的算法那样精确,但是它可能足以满足您的需求。我基本上只是将数据的FFT乘以一个窗口(在本例中为Blackman窗口),对FFT值求平方,找到具有最高值的bin,并使用最大值的对数对峰值进行二次插值和它的两个相邻值来找到基频。我从发现的一些论文中得到了二次插值。

它可以在测试音调上很好地工作,但是不会像上面提到的其他方法那样健壮或准确。可以通过增加块大小来提高精度(或通过减小块大小来降低精度)。块大小应为2的倍数,以充分利用FFT。另外,我只是确定每个块的基本音高,没有重叠。我在写出估计音高的同时使用了PyAudio播放声音。

# Read in a WAV and find the freq's
import pyaudio
import wave
import numpy as np

chunk = 2048

# open up a wave
wf = wave.open('test-tones/440hz.wav', 'rb')
swidth = wf.getsampwidth()
RATE = wf.getframerate()
# use a Blackman window
window = np.blackman(chunk)
# open stream
p = pyaudio.PyAudio()
stream = p.open(format =
                p.get_format_from_width(wf.getsampwidth()),
                channels = wf.getnchannels(),
                rate = RATE,
                output = True)

# read some data
data = wf.readframes(chunk)
# play stream and find the frequency of each chunk
while len(data) == chunk*swidth:
    # write data out to the audio stream
    stream.write(data)
    # unpack the data and times by the hamming window
    indata = np.array(wave.struct.unpack("%dh"%(len(data)/swidth),\
                                         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)
    # read some more data
    data = wf.readframes(chunk)
if data:
    stream.write(data)
stream.close()
p.terminate()
python 2022/1/1 18:31:50 有211人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶