How to mix 8bit/8kHz unsigned linear PCM data in AppsScript? I am having the most difficult time mixing simple unsigned 8-bit/8kHz linear PCM audio samples in JavaScript (AppsScript).  I've tried all the basic maths listed here, employing basic number arrays.


Sign, add, clip, unsign.  Subtract 128 from each byte, add them, clip, then add 128.
Produce the Average, each sample just a[x]+b[x]/2
Viktor T. Toth's, maths linked.


Full example is below.  This will ask you to authorize Google Drive to access the audio samples (no it does NOT touch anything of yours):
https://script.google.com/macros/s/AKfycbzMOWV5Z5soG3uinrFc0WcscNXxsDq9elE9rzG0t703vsvDJZMS/exec

As you can see the 3 mixed results are downright horrible.  I've always assumed the unsigned bytes were just offset by 128.  Not the case?  Do I need to fold half the byte to get a true linear representation?  Does a basic number in JavaScript not translate appropriately into signed/unsigned representation?  If that's the case the Java/AppsScript is somehow properly doing it with the two real samples.


Update
Here is some specific code below, and the output of this is in the link above.  Alas, it simply doesn't quite work (byte folding in JavaScript)?

   var vegaArray = DriveApp.getFileById('0B-e9EqGm0pWPQ3RUTXFyUERDVTA').getBlob().getBytes();
   var fdraArray = DriveApp.getFileById('0B-e9EqGm0pWPaUJQUmFRQWctNG8').getBlob().getBytes();

   for(var i=44;i&lt;vegaArray.length;i++)
     vegaArray[i] = Math.round( ( 2 * (vegaArray[i] + fdraArray[i]) )
       - ( vegaArray[i] * fdraArray[i] / 128 )
       - 256
     ); // for
   // vegaArray[] is the mixed output
Assuming that abyte[] and bbyte[] are two arrays with samples valued from 0-255, this is the solution:

combined = [];
for(i = 0; i &lt; abyte.length; i++)
{   
    sample =  2*(abyte[i] + bbyte[i]) - ((abyte[i]*bbyte[i])/128) - 256
    combined[i] = Math.round(sample);
}


I have a full example with both wav files extracted into arrays (I did this using matlab).  Also I verified that it plays back fine using matlab.

https://jsfiddle.net/4hsfo96g/