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.
I saw here this can be easily done with matlab.
How can this be done with 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. (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:
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:
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.