【发布时间】:2018-11-14 21:03:36
【问题描述】:
我正在编写一个代码来分析由声音演唱的单个音频频率。我需要一种方法来分析音符的频率。目前我正在使用 PyAudio 录制音频文件,存储为.wav,然后立即播放。
import numpy as np
import pyaudio
import wave
# open up a wave
wf = wave.open('file.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)
print(len(data))
print(chunk*swidth)
# 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()
问题出在 while 循环上。由于某种原因,该条件永远不会成立。我打印出两个值(len(data) 和 (chunk*swidth)),它们分别是 8192 和 4096。然后我尝试在 while 循环中使用 2*chunk*swidth ,这引发了这个错误:
File "C:\Users\Ollie\Documents\Computing A Level CA\pyaudio test.py", line 102, in <module>
data))*window
ValueError: operands could not be broadcast together with shapes (4096,) (2048,)
【问题讨论】:
-
Scipy 有信号处理,this answer 讨论其他可能性
-
二进制、十六进制和十进制都代表同一个东西。
0xA=10=1010。仅通过 FFT 运行您的数据不会为您提供基本频率。声音会产生多个频率,因此您需要进行更多的处理和分析才能获得频率。
标签: python numpy audio pyaudio wave