How to join audio files with node js

1

I need to concatenate 2 audio files in wav format with node. I have "audio 1" with 5 seconds of duration and "audio 2 with 5 seconds of duration" I need to generate the "audio 3" file with 5 seconds duration, which contains the contents of audio 1 and audio 2 playing simultaneously.

How can I do this?

    
asked by anonymous 13.02.2018 / 23:04

1 answer

0

You do not want to concatenate you want to mix ...

The simplest way I know is to use 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 with another one that encodes the audio into a wav or mp3 file, I quickly made the code and did not deal with many things that can be important, both audio files have to have exactly of the same size, you can treat in the code if you want later, both decoded files also have to have the same sampling rate ...

I'll explain #

16.02.2018 / 01:38