Skip to content

Instantly share code, notes, and snippets.

@volalex
Created March 26, 2016 21:40
Show Gist options
  • Save volalex/4c62beaa721807dbc139 to your computer and use it in GitHub Desktop.
Save volalex/4c62beaa721807dbc139 to your computer and use it in GitHub Desktop.
private static byte[] mixSignals(byte[] signal, byte[] noise) {
ByteBuffer bb = ByteBuffer.wrap(signal);
bb.order(ByteOrder.LITTLE_ENDIAN);
ShortBuffer sb = bb.asShortBuffer();
short[] signalArray = new short[sb.capacity()];
sb.get(signalArray);
ByteBuffer bb2 = ByteBuffer.wrap(noise);
bb.order(ByteOrder.LITTLE_ENDIAN);
ShortBuffer sb2 = bb2.asShortBuffer();
short[] noiseArray = new short[sb2.capacity()];
sb2.get(noiseArray);
float max = 0;
for (int i=0;i<signalArray.length;i++){
if (noiseArray.length>i){
if (Math.abs(signalArray[i] + noiseArray[i])>max){
max = Math.abs(signalArray[i]+noiseArray[i]);
}
}
}
int a,b,c;
for (int i=0;i<signalArray.length;i++){
a = signalArray[i];
b = noiseArray[i];
c = Math.round(Short.MAX_VALUE *
(a + b) / max);
if (c>Short.MAX_VALUE){
c = Short.MAX_VALUE;
}
else if(c<Short.MIN_VALUE){
c = Short.MIN_VALUE;
}
signalArray[i] = (short) c;
}
byte[] result = new byte[signalArray.length*2];
ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN)
.asShortBuffer().put(signalArray);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment