9

我想要实现的是:我需要声音文件(.wav)的频率值进行分析。我知道很多程序都会给出值的可视化图表(频谱图),但我需要原始数据。我知道这可以用 FFT 完成,并且应该可以很容易地在 python 中编写脚本,但不知道如何准确地做到这一点。因此,假设文件中的信号长度为 0.4 秒,那么我希望多次测量为程序测量的每个时间点提供一个输出作为数组,以及它找到的值(频率)(以及可能的功率(dB))。复杂的是我想分析鸟儿的歌声,它们通常有谐波或信号超过一个频率范围(例如 1000-2000 Hz)。我也希望程序输出这些信息,因为这对于我想对数据进行的分析很重要:)

现在有一段代码看起来非常像我想要的,但我认为它并没有给我我想要的所有值......(感谢贾斯汀皮尔将这个发布到另一个问题:))所以我收集我需要 numpy 和 pyaudio 但不幸的是我不熟悉 python 所以我希望 Python 专家可以帮助我?

源代码:

# 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()
4

2 回答 2

8

如果您只想要 FFT,我不确定这是否是您想要的:

import scikits.audiolab, scipy
x, fs, nbits = scikits.audiolab.wavread(filename)
X = scipy.fft(x)

如果你想要幅度响应:

import pylab
Xdb = 20*scipy.log10(scipy.absolute(X))
f = scipy.linspace(0, fs, len(Xdb))
pylab.plot(f, Xdb)
pylab.show()
于 2010-12-13T17:34:29.720 回答
5

我认为您需要做的是短时傅里叶变换(STFT)。基本上,您执行多个部分重叠的 FFT 并将它们在每个时间点相加。然后你会找到每个时间点的峰值。我自己没有这样做,但我过去曾研究过它,这绝对是前进的方向。

有一些 Python 代码可以在此处此处执行 STFT 。

于 2010-12-13T18:43:07.430 回答