Spaces:
Build error
Build error
Update mix_w_noise.py
Browse files- mix_w_noise.py +44 -0
mix_w_noise.py
CHANGED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from scipy.io.wavfile import read, write
|
3 |
+
import librosa
|
4 |
+
|
5 |
+
|
6 |
+
def mix_audio(signal_file, noise_file, snr):
|
7 |
+
# if the audio is longer than the noise
|
8 |
+
# play the noise in repeat for the duration of the audio
|
9 |
+
signal_samples,s_rate= librosa.load(signal_file, sr=16000)
|
10 |
+
noise_samples, s_rate= librosa.load(noise_file, sr=16000)
|
11 |
+
print(signal_samples.shape, noise_samples.shape)
|
12 |
+
|
13 |
+
signal=np.array(signal_samples,dtype=float)
|
14 |
+
noise= np.array(noise_samples,dtype=float)
|
15 |
+
|
16 |
+
noise = noise[np.arange(len(signal)) % len(noise)]
|
17 |
+
|
18 |
+
# if the audio is shorter than the noi
|
19 |
+
# this is important if loading resulted in
|
20 |
+
# uint8 or uint16 types, because it would cause overflow
|
21 |
+
# when squaring and calculating mean
|
22 |
+
noise = noise.astype(np.float32)
|
23 |
+
signal = signal.astype(np.float32)
|
24 |
+
|
25 |
+
# get the initial energy for reference
|
26 |
+
signal_energy = np.mean(signal**2)
|
27 |
+
noise_energy = np.mean(noise**2)
|
28 |
+
# calculates the gain to be applied to the noise
|
29 |
+
# to achieve the given SNR
|
30 |
+
g = np.sqrt(10.0 ** (-snr/10) * signal_energy / noise_energy)
|
31 |
+
|
32 |
+
# Assumes signal and noise to be decorrelated
|
33 |
+
# and calculate (a, b) such that energy of
|
34 |
+
# a*signal + b*noise matches the energy of the input signal
|
35 |
+
a = np.sqrt(1 / (1 + g**2))
|
36 |
+
b = np.sqrt(g**2 / (1 + g**2))
|
37 |
+
print(g, a, b)
|
38 |
+
|
39 |
+
monaural= a * signal + b * noise
|
40 |
+
write('output.wav', 16000, monaural)
|
41 |
+
|
42 |
+
|
43 |
+
# mix the signals
|
44 |
+
return monaural
|