使用python对wav文件进行加噪

对纯净语音加噪主要为了测试去噪算法的效果,本小程序根据信噪比的定义,批量得到不同信噪比的带噪语音(仅供参考)

注:使用soundfile要下载PySoundFile这个包

import soundfile as sf
import numpy as np
import sys
import os
import re

def add_noise(noisedir,cleandir,snr):
    # noisy
    splitdir=re.split(r"\\",noisedir)
    wavdir="" # 所有wav文件所在路径
    for i in range(len(splitdir) - 1):
        wavdir += splitdir[i] + '/'
    noisydir=wavdir+"noisy/"  # 带噪语音存储路径
    os.mkdir(noisydir)
    # noise
    for noisewav in os.listdir(noisedir):
        noise, fs = sf.read(noisedir+'/'+noisewav)
        noisy_splitdir=noisydir+"add_"+noisewav[:-4]+"/"
        os.mkdir(noisy_splitdir)
    # clean
        for cleanwav in os.listdir(cleandir):
            clean, Fs = sf.read(cleandir+"/"+cleanwav)
            # add noise
            if fs == Fs and len(clean) <= len(noise):
            	# 纯净语音能量
                cleanenergy = np.sum(np.power(clean,2))
                # 随机索引与clean长度相同的noise信号
		ind = np.random.randint(1, len(noise) - len(clean) + 1)
		noiselen=noise[ind:len(clean) + ind]
		# 噪声语音能量
		noiseenergy = np.sum(np.power(noiselen,2))
		# 噪声等级系数
		noiseratio = np.sqrt((cleanenergy / noiseenergy) / (np.power(10, snr * 0.1)))
		# 随机索引与clean长度相同的noise信号
		noisyAudio = clean + noise[ind:len(clean)+ind] * noiseratio
                # write wav
                noisywavname=noisy_splitdir+cleanwav[:-4]+"_"+noisewav[:-4]+"_snr"+str(snr)+".wav"
                sf.write(noisywavname, noisyAudio, 16000)
            else:
                print("fs of clean and noise is unequal or the length of clean is longer than noise's\n")
                sys.exit(-1)

noisedir="C:\\Users\\benla\\Desktop\\新建文件夹\\noise"
cleandir="C:\\Users\\benla\\Desktop\\新建文件夹\\clean"
snr=5
add_noise(noisedir,cleandir,snr)

**

结果:

**
生成的带噪语音:
在这里插入图片描述
加噪前:
在这里插入图片描述
加噪后:
在这里插入图片描述

  • 1
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值