使用python过滤wav文件

Phi*_* R. 9 python audio filtering wav

所以我最近成功构建了一个系统,它将完全用python录制,绘制和播放音频wav文件.现在,我正试图在录制时和开始绘制并将文件输出到扬声器之间进行一些滤波和音频混合.但是,我不知道从哪里开始.现在我要读取初始wav文件,应用低通滤波器,然后将新过滤的数据重新打包到新的wav文件中.这是我用来绘制初始数据的代码.

import matplotlib.pyplot as plt
import numpy as np
import wave
import sys

spf = wave.open('wavfile.wav','r')

#Extract Raw Audio from Wav File
signal = spf.readframes(-1)
signal = np.fromstring(signal, 'Int16')

plt.figure(1)
plt.title('Signal Wave...')
plt.plot(signal)
Run Code Online (Sandbox Code Playgroud)

以下是我用来生成单音测试音频文件的一些代码:

import numpy as np
import wave
import struct

freq = 440.0
data_size = 40000
fname = "High_A.wav"
frate = 11025.0  
amp = 64000.0    

sine_list_x = []
for x in range(data_size):
    sine_list_x.append(np.sin(2*np.pi*freq*(x/frate)))

wav_file = wave.open(fname, "w")

nchannels = 1
sampwidth = 2
framerate = int(frate)
nframes = data_size
comptype = "NONE"
compname = "not compressed"

wav_file.setparams((nchannels, sampwidth, framerate, nframes,
comptype, compname))

for s in sine_list_x:
    wav_file.writeframes(struct.pack('h', int(s*amp/2)))

wav_file.close()
Run Code Online (Sandbox Code Playgroud)

我不确定如何应用所述音频滤镜并重新打包它.我们非常感谢您提供的任何帮助和/或建议.

pie*_*cus 32

第一步:您需要什么样的音频滤波器?

选择过滤后的乐队

对于以下步骤,我假设您需要一个低通滤波器.

选择截止频率

截止频率是你的信号将通过-3dB衰减频率.

你的榜样信号的440Hz,让我们选择一个截止频率400Hz的.然后通过低通400Hz滤波器衰减440Hz信号(大于-3dB).

选择您的过滤器类型

根据这个其他stackoverflow答案

滤波器设计超出了Stack Overflow的范围 - 这是一个DSP问题,而不是编程问题.过滤器设计由任何DSP教科书涵盖 - 转到您的图书馆.我喜欢Proakis和Manolakis的数字信号处理.(Ifeachor和Jervis的数字信号处理也不错.)

举一个简单的例子,我建议使用移动平均滤波器(对于简单的低通滤波器).

移动平均线

在数学上,移动平均是一种卷积,因此它可以被视为信号处理中使用的低通滤波器的一个例子

此移动平均低通滤波器是一个基本滤波器,它易于使用和理解.

移动平均线的参数是窗口长度.

之间的关系的移动平均窗口的长度和截止频率需要点点数学和说明在这里

代码将是

import math

sampleRate = 11025.0 
cutOffFrequency = 400.0
freqRatio = (cutOffFrequency/sampleRate)

N = int(math.sqrt(0.196196 + freqRatio**2)/freqRatio)
Run Code Online (Sandbox Code Playgroud)

因此,在示例中,窗口长度将为11

第二步:对过滤器进行编码

手工制作的移动平均线

看看如何在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)
Run Code Online (Sandbox Code Playgroud)

使用lfilter

或者,正如dpwilson所建议的那样,我们也可以使用lfilter

win = numpy.ones(N)
win *= 1.0/N
filtered = scipy.signal.lfilter(win, [1], signal).astype(channels.dtype)
Run Code Online (Sandbox Code Playgroud)

第三步:让我们把它放在一起

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()
Run Code Online (Sandbox Code Playgroud)

  • @user13107请参阅`nfilter`中的https://docs.scipy.org/doc/scipy/reference/ generated/scipy.signal.lfilter.html#scipy-signal-lfilter,我们使用IIR或FIR滤波器的更通用概念。这是根据方程“a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[M”的多项式定义滤波器]*x[nM] - a[1]*y[n-1] - ... - a[N]*y[nN]` 我们使用 `b = win, a = [1], x = signal`那么等式是 `1*y[n] = win[0]*signal[n] + win[1]*signal[n-1] + ... + win[M]*signal[nM]` 就像使用用大锤敲开坚果,但它确实有效! (2认同)