简体   繁体   English

如何使用python向WAV文件添加噪音?

[英]How to add noise to wav file using python?

I have a clean wav, and a wav containing a pre-generated noise, and I would like to add the noise to the clean wav file, to create a noisy wav. 我有一个干净的WAV,并且WAV包含一个预先生成的噪音,我想将噪音添加到干净的WAV文件中,以创建一个嘈杂的WAV。

I saw here this can be easily done with matlab. 我在这里看到可以使用matlab轻松完成。

How can this be done with python? 如何使用python完成此操作?

import numpy as np
from scikits.audiolab import wavread, wavwrite

data1, fs1, enc1 = wavread("file1.wav")
data2, fs2, enc2 = wavread("file2.wav")

assert fs1 == fs2
assert enc1 == enc2
result = 0.5 * data1 + 0.5 * data2

wavwrite(result, 'result.wav')

However, if you have different a sampling rate ( fs* ) or encoding ( enc* ) then you may have to try something more complex. 但是,如果您使用不同的采样率( fs* )或编码( enc* ),则可能必须尝试更复杂的方法。 (Sourced from here ) (来自此处

Additional 额外

If you data* arrays are of different sizes, you could either just match the shortest array to a subset of the longer array: 如果data*数组的大小不同,则可以将最短的数组与较长的数组的子集进行匹配:

min_size = min(len(data1), len(data2))

result = 0.5 * data1[:min_size] + 0.5 * data2[:min_size]

or you could wrap the shortest array so that it matches the length of the longest array: 或者,您可以wrap最短的数组,使其与最长的数组的长度匹配:

short, long = (data1, data2) if len(data1) < len(data2) else (data2, data1)
n = len(long) / len(short)
new_array = np.tile(short, n)

result = 0.5 * long[:n] * 0.5 * new_array

These notes are outside the scope of your question. 这些说明不在您的问题范围内。 If you have further troubles you should probably mark this as solved and open up a new question. 如果您还有其他麻烦,您可能应该将其标记为已解决,并提出一个新问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM