第一步:你需要什么样的音频过滤器?
选择过滤波段
对于以下步骤,我假设您需要一个低通滤波器。
选择您的截止频率
Cutoff frequency 是信号衰减 -3dB 的频率。
您的示例信号是 440Hz,所以让我们选择 400Hz 的 Cutoff frequency。然后,您的 440Hz 信号会被低通 400Hz 滤波器衰减(超过 -3dB)。
选择您的过滤器类型
根据this other stackoverflow answer
滤波器设计超出了 Stack Overflow 的范围 - 那是一个 DSP
问题,不是编程问题。过滤器设计涵盖了任何
DSP 教科书 - 去你的图书馆。我喜欢 Proakis 和 Manolakis
数字信号处理。 (Ifeachor 和 Jervis 的数字信号
处理也不错。)
进入一个简单的例子,我建议使用移动平均滤波器(用于简单的低通滤波器)。
见Moving average
在数学上,移动平均是一种卷积,因此可以将其视为信号处理中使用的低通滤波器的示例
这个移动平均低通滤波器是一个基本的滤波器,非常容易使用和理解。
移动平均线的参数是窗口长度。
moving average 窗口长度和Cutoff frequency 之间的关系需要一点数学知识,并解释了here
代码将是
import math
sampleRate = 11025.0
cutOffFrequency = 400.0
freqRatio = cutOffFrequency / sampleRate
N = int(math.sqrt(0.196201 + freqRatio**2) / freqRatio)
因此,在示例中,窗口长度将为 12
第二步:编码过滤器
手工移动平均线
见specific discussion on how to create a moving average in python
Alleo 的解决方案是
def running_mean(x, windowSize):
cumsum = numpy.cumsum(numpy.insert(x, 0, 0))
return (cumsum[windowSize:] - cumsum[:-windowSize]) / windowSize
filtered = running_mean(signal, N)
使用 lfilter
或者,正如dpwilson 所建议的,我们也可以使用lfilter
win = numpy.ones(N)
win *= 1.0/N
filtered = scipy.signal.lfilter(win, [1], signal).astype(channels.dtype)
第三步:让我们把它们放在一起
import matplotlib.pyplot as plt
import numpy as np
import wave
import sys
import math
import contextlib
fname = 'test.wav'
outname = 'filtered.wav'
cutOffFrequency = 400.0
# from http://stackoverflow.com/questions/13728392/moving-average-or-running-mean
def running_mean(x, windowSize):
cumsum = np.cumsum(np.insert(x, 0, 0))
return (cumsum[windowSize:] - cumsum[:-windowSize]) / windowSize
# from http://stackoverflow.com/questions/2226853/interpreting-wav-data/2227174#2227174
def interpret_wav(raw_bytes, n_frames, n_channels, sample_width, interleaved = True):
if sample_width == 1:
dtype = np.uint8 # unsigned char
elif sample_width == 2:
dtype = np.int16 # signed 2-byte short
else:
raise ValueError("Only supports 8 and 16 bit audio formats.")
channels = np.fromstring(raw_bytes, dtype=dtype)
if interleaved:
# channels are interleaved, i.e. sample N of channel M follows sample N of channel M-1 in raw data
channels.shape = (n_frames, n_channels)
channels = channels.T
else:
# channels are not interleaved. All samples from channel M occur before all samples from channel M-1
channels.shape = (n_channels, n_frames)
return channels
with contextlib.closing(wave.open(fname,'rb')) as spf:
sampleRate = spf.getframerate()
ampWidth = spf.getsampwidth()
nChannels = spf.getnchannels()
nFrames = spf.getnframes()
# Extract Raw Audio from multi-channel Wav File
signal = spf.readframes(nFrames*nChannels)
spf.close()
channels = interpret_wav(signal, nFrames, nChannels, ampWidth, True)
# get window size
# from http://dsp.stackexchange.com/questions/9966/what-is-the-cut-off-frequency-of-a-moving-average-filter
freqRatio = (cutOffFrequency/sampleRate)
N = int(math.sqrt(0.196196 + freqRatio**2)/freqRatio)
# Use moviung average (only on first channel)
filtered = running_mean(channels[0], N).astype(channels.dtype)
wav_file = wave.open(outname, "w")
wav_file.setparams((1, ampWidth, sampleRate, nFrames, spf.getcomptype(), spf.getcompname()))
wav_file.writeframes(filtered.tobytes('C'))
wav_file.close()