You don’t want to concatenate you want to mix ...
The simplest way I know is to use the web-audio-api
Install with:
npm install web-audio-api
Decode both files and add the values of the two vectors:
var AudioContext = require('web-audio-api').AudioContext
context = new AudioContext
var samplerate;
var pcmdata1 = [] ;
var pcmdata2 = [] ;
var mix = [];
var soundfile1 = "sounds/sound1.wav"
var soundfile2 = "sounds/sound2.wav"
decodeSoundFile1(soundfile1);
decodeSoundFile2(soundfile2);
mixer();
playSound(mix)
//decodificando os dois arquivos
function decodeSoundFile1(soundfile){
console.log("decoding file ", soundfile, " ..... ")
fs.readFile(soundfile, function(err, buf) {
if (err) throw err
context.decodeAudioData(buf, function(audioBuffer) {
console.log(audioBuffer.numberOfChannels, audioBuffer.length, audioBuffer.sampleRate, audioBuffer.duration);
pcmdata1 = (audioBuffer.getChannelData(0)) ;
samplerate=audioBuffer.sampleRate;
}, function(err) { throw err })
})
}
function decodeSoundFile2(soundfile){
console.log("decoding file ", soundfile, " ..... ")
fs.readFile(soundfile, function(err, buf) {
if (err) throw err
context.decodeAudioData(buf, function(audioBuffer) {
console.log(audioBuffer.numberOfChannels, audioBuffer.length, audioBuffer.sampleRate, audioBuffer.duration);
pcmdata2 = (audioBuffer.getChannelData(0)) ;
}, function(err) { throw err })
})
}
//mixando os arquivos
function mixer() {
for (var i = 0; i < pcmdata1.length; i++)
mix[i] = pcmdata1[i] + pcmdata2[i]
}
//tocando o áudio mixado no browser
function playSound(arr) {
var buf = new Float32Array(arr.length)
for (var i = 0; i < arr.length; i++) buf[i] = arr[i]
var buffer = context.createBuffer(1, buf.length, samplerate)
buffer.copyToChannel(buf, 0)
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start(0);
}
of course you can replace the function that plays the audio by another that encodes the audio in a wav or mp3 file, I quickly made the code and did not treat many things that can be important, both audio files have to be exactly the same size, you can treat in code if you want later, both decoded files also have to possess the same sample rate ...
I’ll explain here as this is done in java, the logic and the steps are the same for any language!