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.

  • 2
    $\begingroup$ What have you tried? What tutorials/books/online resources have you read? This is a pretty basic task that is well documented. $\endgroup$
    – MBaz
    Apr 10, 2019 at 17:26
  • $\begingroup$ 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. $\endgroup$ Apr 10, 2019 at 19:22
  • $\begingroup$ Try this, they discussed similar topic to yours $\endgroup$
    – user41623
    Apr 11, 2019 at 6:41
  • $\begingroup$ Using sox: sound.stackexchange.com/questions/45868/… $\endgroup$
    – tonys
    May 9, 2020 at 16:00

2 Answers 2


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.

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)

samplerate, data = wavfile.read(os.path.join(record_path, WAV_FILE_NAME))
assert samplerate == FRAME_RATE
filtered = np.apply_along_axis(bandpass_filter, 0, data).astype('int16')
wavfile.write(os.path.join(record_path, f'filtered_{WAV_FILE_NAME}'), samplerate, filtered)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.