Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically merging two pieces of audio

I have two arrays of samples of two different audio clips. If I just programmatically add them together will this be the equivalent of layering one track over another in an audio editing suite? Like if I have one audio clip of bass the other of a drum and I want them playing together.

I would probably do something like this:

 for (int i = 0; i < length_of_array; i++){
   final_array[i] = first_array[i] + second_array[i];
 }

If it is not done this way, could I get some indication of what would be the correct way?

like image 210
Eric Brotto Avatar asked Dec 03 '22 09:12

Eric Brotto


1 Answers

This IS a correct way. Merging is called MIXING in audio jargon.

BUT:

If your samples are short (16 bit signed) - you will have to use int (32 bit signed) for addition and then clip the samples manually. If you don't, your values will wrap and you'll have so much fun listening to what you did :)

Here comes the code:

short first_array[1024];
short second_array[1024];
short final_array[1024];
for (int i = 0; i < length_of_array; i++)
{
    int mixed=(int)first_array[i] + (int)second_array[i];
    if (mixed>32767) mixed=32767;
    if (mixed<-32768) mixed=-32768;
    final_array[i] = (short)mixed;
}

In MOST cases you don't need anything else for normal audio samples, as the clipping will occur in extremely rare conditions. I am talking this from practice, not from theory.

like image 99
Daniel Mošmondor Avatar answered Dec 29 '22 13:12

Daniel Mošmondor