python代码已上传
https://download.csdn.net/download/qq_21288703/12526834
MATLAB
close all;clear;clc;
SNR = 5;
[signal,fs] = audioread(inputpath);
signal = signal(1:10000);
[noise,fs_n] = audioread('white.wav');
signal_len = size(signal,1);
NOISE = noise(1: nx);
NOISE = NOISE - mean(NOISE);
signal_power = 1/nx*sum(signal.*signal);
noise_variance = signal_power / ( 10^(SNR/10) );
NOISE=sqrt(noise_variance)/std(NOISE)*NOISE;
Y = signal + NOISE;
t = (0: length(signal) - 1) / fs;
subplot(2,1,1); plot(t,signal); % 绘制原波形图
subplot(2,1,2); plot(t,Y); % 绘制加入噪音后波形图
python读取/写入wav
import soundfile as sf
signal, fs = sf.read(input_path)
sf.write(output_path, signal_with_noise, fs)
python
待处理音频太长了,直接算的话会溢出,所以分成了100段。
import soundfile as sf
import os
def add_white1(input_path, output_path,SNR, num_of_group):
signal, fs = sf.read(input_path)
noise0, fs_n = sf.read('white.wav')
noise = noise0 - np.mean(noise0)
#分组
nx = len(signal)
h = 0
group_len = int(nx / num_of_group)
grouped_signal = []
grouped_noise = []
for i in range(num_of_group):
obj_signal = signal[h:h + group_len]
grouped_signal.append(obj_signal)
h = h + group_len
obj_noise = noise[0:group_len]
grouped_noise.append(obj_noise)
grouped_signal_power = []
grouped_noise_variance = []
grouped_NOISE = []
a = float(SNR / 10)
for i in range(num_of_group):
cur_signal = grouped_signal[i]
cur_noise = grouped_noise[i]
grouped_signal_power.append(1 / group_len * sum(cur_signal * cur_signal))
grouped_noise_variance.append(grouped_signal_power[i] / (10 ** a))
grouped_NOISE.append((cmath.sqrt(grouped_noise_variance[i]) / np.std(cur_noise)) * cur_noise)
array_signal = np.array(grouped_signal).flatten()
array_NOISE = np.array(grouped_NOISE).flatten()
array_NOISE = array_NOISE.real
signal_with_noise = (array_signal + array_NOISE)
print(np.array(signal_with_noise).shape)
sf.write(output_path, signal_with_noise, fs)
maindir = ‘’
files = os.listdir(maindir)
for filename in files:
add_white1(input + filename, output + filename , 5, 200)