# Bandpass filter for audio wav file

How do I apply a bandpass filter on an audio file which is in wav format? And write back the filtered data in a new wav file for further analysis.

• What have you tried? What tutorials/books/online resources have you read? This is a pretty basic task that is well documented.
– MBaz
Apr 10, 2019 at 17:26
• So I've looked/tried/read ThinkDSP by AllenDowney but it relies heavily on the thinkDSP library. I want a more robust solution. I have a matlab code that works wonderfully. I want to implement it in python as well. Apr 10, 2019 at 19:22
• Try this, they discussed similar topic to yours
– user41623
Apr 11, 2019 at 6:41
• May 9, 2020 at 16:00

Consider looking at this StackOverflow answer which provides the full code for creating a Butterworth bandpass filter. In the sample code the answerer provides, the filter is applied to a manually constructed simplistic signal x. If you substitute this signal with your own NumPy array, it should achieve the intended effect.

WAV files can be quickly made into NumPy arrays, consider using the librosa module. librosa.core.load will be what you use. To write out the filtered signal, simply use librosa.output.write_wav.

• Jan 22, 2021 at 15:56
import numpy as np
import os
from scipy.io import wavfile

WAV_FILE_NAME = 'my_audio.wav'
lowcut = 1200.0
highcut = 1300.0
FRAME_RATE = 16000

def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='band')
return b, a

def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
y = lfilter(b, a, data)
return y

def bandpass_filter(buffer):
return butter_bandpass_filter(buffer, lowcut, highcut, FRAME_RATE, order=6)