In this notebook I use the noisereduce Python package to add and remove noise from audio.

Import packages¶

In [1]:
import IPython
from scipy.io import wavfile
import noisereduce as nr
import soundfile as sf
from noisereduce.generate_noise import band_limited_noise
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

Load audio¶

In [2]:
file_name = "speaker.wav"
raw_audio, rate = sf.read(file_name)
print("Sampling frequency is: " + str(rate) + " Hz")
Sampling frequency is: 44100 Hz
In [3]:
IPython.display.Audio(data=raw_audio, rate=rate)
Out[3]:
Your browser does not support the audio element.
In [4]:
time_axis = np.linspace(0, len(raw_audio) / rate, num = len(raw_audio))

plt.figure(figsize = (12, 4))
plt.plot(time_axis, raw_audio, color = "g")
plt.title(file_name + " (raw)")
plt.xlabel("Time (seconds)")
plt.ylabel("Amplitude")
plt.show()
No description has been provided for this image

Add noise to audio¶

In [5]:
noise = band_limited_noise(min_freq = 2000
                           ,max_freq = 12000
                           ,samples = len(raw_audio)
                           ,samplerate = rate)*10

audio_with_noise = raw_audio + noise
In [6]:
IPython.display.Audio(data = audio_with_noise
                      ,rate = rate)
Out[6]:
Your browser does not support the audio element.
In [7]:
time_axis = np.linspace(0, len(audio_with_noise) / rate, num = len(audio_with_noise))

plt.figure(figsize = (12, 4))
plt.plot(time_axis, audio_with_noise, color = "r")
plt.title(file_name + " (with added noise)")
plt.xlabel("Time (seconds)")
plt.ylabel("Amplitude")
plt.show()
No description has been provided for this image

Remove noise from audio¶

In [8]:
audio_reduced_noise = nr.reduce_noise(y = audio_with_noise
                                    ,sr = rate
                                    ,n_std_thresh_stationary = 0.8
                                    ,stationary = True)
In [9]:
IPython.display.Audio(data = audio_reduced_noise
                      ,rate = rate)
Out[9]:
Your browser does not support the audio element.
In [10]:
plt.figure(figsize=(12, 4))
plt.plot(time_axis, audio_with_noise, color = "r", label = "With Added Noise")
plt.plot(time_axis, audio_reduced_noise, color = "y", label = "With Noise Reduction")
plt.title(file_name + " (with added noise and with stationary noise removal)")
plt.xlabel("Time (seconds)")
plt.ylabel("Amplitude")
plt.legend()
plt.show()
No description has been provided for this image