pythonaudiowavlowpass-filterbutterworth

audio file sounds bad/noisy after passing through low pass filter


I am trying to pass my audio through low pass filter, so as to filter out noise from it. However, the output of the wav is very noisy, and I am unable to understand why. Find the original and filtered wav and their resp. spectrograms below link. enter link description here

The code I have used is:

#https://stackoverflow.com/questions/25191620/creating-lowpass-filter-in-scipy-understanding-methods-and-units
import numpy as np
from scipy.signal import butter, lfilter, freqz, filtfilt
from matplotlib import pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a


def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y

frq, data = wavfile.read('original.wav')
# Filter requirements.
order = 5
fs =  frq   # sample rate, Hz
cutoff = 4000  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
#b, a = butter_lowpass(cutoff, fs, order)


# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
wavfile.write('LPF_filttered.wav', frq, y)

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()

# First make some data to be filtered.        # seconds
n = len(data) # total number of samples
t = np.linspace(0, 1.0 , n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

1) Is this the correct way to implement a filter. Or am I doing something wrong? Because the resulting audios are way too distorted.

2) What is the correct way, so that I will get the noise-free audio files

Thanks in advance.


Solution

  • Replace the line where you save the output audio with the following:

    wavfile.write('LPF_filttered.wav', frq, np.int16(y/np.max(np.abs(y)) * 32767))