I have two wav files that I want to mix together to form one wav file. They are both the same samples format etc...
Been searching google endlessly.
I would prefer to do it using the wave module in python.
How can this be done?
I have two wav files that I want to mix together to form one wav file. They are both the same samples format etc...
Been searching google endlessly.
I would prefer to do it using the wave module in python.
How can this be done?
LIBROSA SOLUTION
import librosa
import IPython as ip
y1, sample_rate1 = librosa.load(audio1, mono=True)
y2, sample_rate2 = librosa.load(audio2, mono=True)
# MERGE
librosa.display.waveplot((y1+y2)/2, sr=int((sample_rate1+sample_rate2)/2))
# REPRODUCE
ip.display.Audio((y1+y2)/2, rate=int((sample_rate1+sample_rate2)/2))
You guys like numpy, no? Below is a solution that depends on wave and numpy. Raw bytes in two files './file1.wav' and './file2.wav' are added. It's probably good to apply np.clip to mix before converting back to int-16 (not included).
import wave
import numpy as np
# load two files you'd like to mix
fnames =["./file1.wav", "./file2.wav"]
wavs = [wave.open(fn) for fn in fnames]
frames = [w.readframes(w.getnframes()) for w in wavs]
# here's efficient numpy conversion of the raw byte buffers
# '<i2' is a little-endian two-byte integer.
samples = [np.frombuffer(f, dtype='<i2') for f in frames]
samples = [samp.astype(np.float64) for samp in samples]
# mix as much as possible
n = min(map(len, samples))
mix = samples[0][:n] + samples[1][:n]
# Save the result
mix_wav = wave.open("./mix.wav", 'w')
mix_wav.setparams(wavs[0].getparams())
# before saving, we want to convert back to '<i2' bytes:
mix_wav.writeframes(mix.astype('<i2').tobytes())
mix_wav.close()
Try the Echo Nest Remix API:
from echonest import audio
from util import *
def mixSound(fname1,fname2,f_out_name):
f1 = audio.AudioData(fnem1)
f2 = audio.AudioData(fnem2)
f_out = audio.mix(f1,f2)
f_out.encode(foutnem, True)
If it complains about codecs, check https://superuser.com/questions/196857/how-to-install-libmp3lame-for-ffmpeg.