我想要实现的是:我需要声音文件(.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()