【发布时间】:2011-05-24 19:22:41
【问题描述】:
我想要实现的是:我需要声音文件 (.wav) 的频率值进行分析。我知道很多程序都会给出值的可视化图表(频谱图),但我需要原始数据。我知道这可以用 FFT 完成,并且应该可以很容易地在 python 中编写脚本,但不知道如何准确地做到这一点。 因此,假设文件中的信号长度为 0.4 秒,那么我希望多次测量为程序测量的每个时间点提供一个输出作为数组,以及它找到的值(频率)(以及可能的功率(dB))。复杂的是我想分析鸟儿的歌声,它们通常有谐波或信号超过一个频率范围(例如 1000-2000 Hz)。我希望程序也能输出这些信息,因为这对于我想对数据进行的分析很重要:)
现在有一段代码看起来很像我想要的,但我认为它并没有给我想要的所有值....(感谢 Justin Peel 将其发布到另一个问题 :))所以我认为我需要 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()
【问题讨论】:
-
您尝试过“搜索”吗?有人问过这个问题。以stackoverflow.com/questions/2648151/python-frequency-detection 为例。
-
是的,这至少是过去两周内这个问题第 5 次出现在 SO 上。
-
是的,我已经搜索并环顾四周.. 但没有找到我需要的确切答案。但是在进一步搜索时,我发现了一个完全免费的程序:)如果其他人阅读此问题并希望做类似的事情,则声音分析专业人士。您可以使用此程序导出到 Excel 或 matlab 来获取数据(频率等)!
标签: python audio numpy fft frequency