好的,我想做的是一种音频处理软件,它可以检测流行频率,如果频率播放时间足够长(几毫秒),我知道我得到了肯定的匹配。我知道我需要使用 FFT 或类似的东西,但在这个数学领域我很烂,我确实搜索了互联网,但没有找到只能做到这一点的代码。
我试图实现的目标是让自己成为一个自定义协议来通过声音发送数据,每秒需要非常低的比特率(5-10bps),但我在传输端也非常有限,因此接收软件需要能够自定义(不能使用实际的硬件/软件调制解调器)我也希望这只是软件(除了声卡没有额外的硬件)
非常感谢您的帮助。
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()
如果您打算使用FSK(频移键控)对数据进行编码,则最好使用Goertzel 算法,这样您就可以只检查所需的频率,而不是完整的 DFT/FFT。
您可以从此处找到声音上滑动窗口的频谱,然后通过从此处找到该频带的频谱曲线下的区域来检查流行频带的存在。
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import auc
np.random.seed(0)
# Sine sample with a frequency of 5hz and add some noise
sr = 32 # sampling rate
y = np.linspace(0, 5 * 2*np.pi, sr)
y = np.tile(np.sin(y), 5)
y += np.random.normal(0, 1, y.shape)
t = np.arange(len(y)) / float(sr)
# Generate frquency spectrum
spectrum, freqs, _ = plt.magnitude_spectrum(y, sr)
# Calculate percentage for a frequency range
lower_frq, upper_frq = 4, 6
ind_band = np.where((freqs > lower_frq) & (freqs < upper_frq))
plt.fill_between(freqs[ind_band], spectrum[ind_band], color='red', alpha=0.6)
frq_band_perc = auc(freqs[ind_band], spectrum[ind_band]) / auc(freqs, spectrum)
print('{:.1%}'.format(frq_band_perc))
# 19.8%
虽然我之前没有尝试过使用 Python 进行音频处理,但也许您可以基于SciPy(或其子项目 NumPy)构建一些东西,这是一个用于高效科学/工程数值计算的框架?您可以先查看scipy.fftpack的 FFT。