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]:
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()
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]:
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()
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]:
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()