1

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?

speller
  • 1,641
  • 2
  • 20
  • 27

1 Answers1

1
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.

Community
  • 1
  • 1
danodonovan
  • 19,636
  • 10
  • 70
  • 78
  • This doesn't work. data1 and data2 don't have the same length. So I've only taken data[:100000], and what I get for result is a very short file (400KB) which contains a VERY slow sample of something. You can try it yourself, you'll see. – speller Mar 03 '13 at 23:31
  • You might need to verify that the resulting wave file has the correct sampling rate, word size, etc.. Since danodonovan's program doesn't explicitly set these parameters, its very likely that the defaults aren't what you want. – sizzzzlerz Mar 03 '13 at 23:55