from scipy.io import wavfile
import os
import librosa
import numpy as np
# 加正态分布的噪声
def add_noise_normal(filepath,outfilepath):
    data,fs = librosa.load(filepath)
    wn = np.random.normal(0, 2, len(data))
    data_noise = np.where(data != 0.0, data.astype('float64') + 0.02 * wn, 0.0).astype(np.float32)
    wavfile.write(outfilepath, 16000, data_noise)

# 背景噪声
def add_noise_background(filepath,outfilepath,noise_path):
    wn,fss = librosa.load(filepath)
    wn=wn[:,0]/np.max(wn[:,0])
    data,fs = librosa.load(filepath)
    data = data[:,0]/np.max(data[:,0])
    data_noise = np.where(data != 0.0, data.astype('float64') +wn[:len(data)], 0.0).astype(np.float32)
    wavfile.write(outfilepath, 16000, data_noise)


# 降采样(采样率不变而是某些值进行了为0操作)
def add_noise_down_sample(filepath,outfilepath):
    data,fs = librosa.load(filepath)

    data_noise = np.where(data != 0.0, data.astype('float64')-10*np.mean(data), 0.0).astype(np.float32)
    wavfile.write(outfilepath, 16000, data_noise)


# 改变声调
def bian_diao(filepath,n_steeps,outfilepath):
    y,sr = librosa.load(filepath)

    # 通过移动音调变声 ,14是上移14个半步, 如果是 -14 下移14个半步
    b = librosa.effects.pitch_shift(y, sr,n_steps=n_steeps)
    wavfile.write(outfilepath, 16000, b)

# 改变音色
def bian_yin_se(filepath,n_steeps,outfilepath):
    y,sr = librosa.load(filepath)


    # stft 短时傅立叶变换
    a = librosa.stft(y)
    length = len(a)

    # 改变或去除某些值,可以改变声音 选择频率
    r_a = a[10:length-n_steeps]

    # istft 逆短时傅立叶变换,变回去
    b = librosa.istft(r_a)
    wavfile.write(outfilepath, 16000, 10 * b)








if __name__ == '__main__':
    pass