Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
83 lines (66 sloc) 2.37 KB
import soundfile as sf
import numpy as np
error_range = .1
def norm(data):
max_amp = np.std(data) # np.max(np.abs(data))
return (data-data.mean()) / max_amp
def scale_clean_noisy(clean,noisy):
max_amp = np.max(np.abs([clean, noisy]))
mix_scale = 1 / max_amp * (np.random.rand()*0.1 + 0.8)
X = clean * mix_scale
Y = noisy * mix_scale
return X, Y
def cal_snr_db(signal, noise):
Es = (signal**2).mean()
Vn = np.var(noise)
return 10*np.log10(Es/Vn)
def cal_power(signal, sr=16000):
p = (signal**2).mean()
return p
def snr_mix_power(clean, noise, snr):
clean_ = norm(clean)
noise_ = norm(noise)
pclean = cal_power(clean_)
pnoise = cal_power(noise_)
noisescalar = np.sqrt(pclean/pnoise/10**(snr/10))
noise_ = noise_ * noisescalar
# print(cal_snr_db(clean_,noise_))
assert abs(cal_snr_db(clean_,noise_) - snr) < error_range
noisy = clean_ + noise_
return scale_clean_noisy(clean_,noisy)
def snr_mix_amplitude(clean, noise, snr):
clean_ = norm(clean)
noise_ = norm(noise)
rmsclean = (clean_**2).mean()**0.5
rmsnoise = (noise_**2).mean()**0.5
# Set the noise level for a given SNR
noisescalar = rmsclean / (10**(snr/20)) / rmsnoise
noise_ = noise_ * noisescalar
# print(cal_snr_db(clean_,noise_))
assert abs(cal_snr_db(clean_,noise_) - snr) < error_range
noisy = clean_ + noise_
return scale_clean_noisy(clean_,noisy)
def snr_both_mix(clean,noise,snr):
clean_ = norm(clean)
noise_ = norm(noise)
clean_snr = snr / 2
noise_snr = -snr / 2
cleanscalar = 10 ** (clean_snr / 20)
noisescalar = 10 ** (noise_snr / 20)
clean_ = clean_ * cleanscalar
noise_ = noise_ * noisescalar
# print(cal_snr_db(clean_,noise_))
assert abs(cal_snr_db(clean_,noise_) - snr) < error_range
noisy = clean_ + noise_
return scale_clean_noisy(clean_,noisy)
if __name__ == "__main__":
clean, sr_c = sf.read('clean.wav')
noise, sr_n = sf.read('noise.wav')
assert len(clean) == len(noise)
assert sr_c == sr_n
clean, noisy = snr_mix_power(clean,noise,3.3)
clean, noisy = snr_mix_amplitude(clean,noise,8.6)
clean, noisy = snr_both_mix(clean,noise,-0.3)
sf.write('clean_test.wav',clean,sr_c)
sf.write('noisy_test.wav',noisy,sr_c)
# print("All Passed!")
You can’t perform that action at this time.