Search code examples
pythonaudiolibrosa

Add noise to Audio File and Reconvert the Noisy signal using Librosa Python


I am adding noise to a signal using librosa but after adding noise I am unable to save the signal back as wav file.

My code is as follows:

import librosa

import matplotlib.pyplot as plt
import numpy as np
import math

file_path = r'path\to\file'
#
#
signal, sr = librosa.load(file_path, sr = 16000)
# plt.plot(signal)
#
RMS=math.sqrt(np.mean(signal**2))

STD_n= 0.001
noise=np.random.normal(0, STD_n, signal.shape[0])
#
# # X=np.fft.rfft(noise)
# # radius,angle=to_polar(X)
#
signal_noise = signal+noise

I want to convert signal_noise as a wav file. I tried different librosa functions but I am unable to find one. I tried using scipy.io.wavfile.write but I was getting an error probably because Librosa generates Normalized audio while Scipy doesn't.


Solution

  • You can do it using the soundfile library. Add these lines to ur code:

    import soundfile
    soundfile.write('filename.wav',signal_noise,16000)
    

    Parameters:

    • The 1st parameter is the file name
    • The 2nd parameter is the audio that you want to save
    • The 3rd parameter is the sample rate

    Hope that this helps you!