问题
I would like to mix audio byte array, but I didn't succeed to sum the array.(note i already added some silent bytes of 0 as padding before).
I have an ArrayList
of byte[]
which contains:
- the first byte[] is header (44 bytes).
- Following byte[] are raw data byte array to be mixed
Here is my code:
ArrayList<byte[]> ListAudio = new ArrayList<byte[]>();
byte[] header= WriteHeader(); //wav header 44 bytes
ListAudio.add(header);
for (byte[] b : audioTreatment.ListDataByte) {
ListAudio.add(b);
}
//calculate total length of audio
int length = 0;
for (byte[] array : ListAudio) {
length += array.length;
}
final int len = length;
final byte[] mixBytes = new byte[len];
for (byte[] array : ListAudio) {
for (int i = 44; i < len; ++i) {
mixBytes[i] += array[i];
// mixBytes[i]=(byte) ((bytes1[i]+bytes2[i]) / 2);
}
}
I found somewhere that the method to mix digital byte array is :
mixBytes[i]=(byte) ((bytes1[i]+bytes2[i]) / 2);
I don't arrive to include the calcul above, to sum the byte array. How can i sum the bytes array from my ArrayList ?
回答1:
you have to declare your sources to merge them
byte[] source1 = ListAudio.get(0); //first from list
byte[] source2 = ListAudio.get(1); //second from list
int length = Math.min(source1.length, source2.length);//length of new array
length = length - 44; //skipping 44 byte
byte[] dest = new byte[length];
for(int index = 0; index < length; index ++){
byte b1 = source1[index+44];
byte b2 = source2[index+44];
dest[index] = (byte) ((b1+b2) / 2);
}
That would merge the first two byte[] from your list.
If you want to merge other sources you can change them by selecting other byte[]
from your List.
HINT
The length of the destination is declared as Math.min(a,b)
but you can fill missing bytes with zeros if you want...
if you want to merge all arrays, you have to adjust your merge operation
mixing two bytes: mixBytes[i]=(byte) ((bytes1[i]+bytes2[i]) / 2);
mixing three bytes: mixBytes[i]=(byte) ((bytes1[i]+bytes2[i]+bytes3[i]) / 3);
mixing N bytes: mixBytes[i]=(byte) ((bytes1[i]+bytes2[i]+bytes3[i]+...+bytesN[i]) / N);
ok, for your code snipped it would be:
int length = ...;//length of result, either min or max as mentioned above, see HINT
byte[] mixBytes = new byte[length];
int amountAudio = ListAudio.size(); //amount of tracks in your list aka 'N'
int sum;
for(int index = 0; index < length; index++){
sum = 0;
for(byte[] source: ListAudio){
//adding all byte into one big integer
sum = sum + source[index]; //NOTE: watch for indexOutOfBoundsException
}
//afterward divide the big int through amount of Audio tracks in your list
mixBytes[index] = (byte)(sum / amountAudio);
}
来源:https://stackoverflow.com/questions/39613665/mix-byte-array-android