Skip to content

Instantly share code, notes, and snippets.

@kswlee
Created December 31, 2013 02:32
Show Gist options
  • Save kswlee/8191610 to your computer and use it in GitHub Desktop.
Save kswlee/8191610 to your computer and use it in GitHub Desktop.
private int downSample(float factor, byte [] in, byte [] out) {
int bytes = 4; // one audio sample is 32bits
factor = 1.0f / factor;
int downSampleCount = (int) (((in.length / bytes)) * factor);
int ouputSampleCount = 0;
for (int i = 0; i < downSampleCount; ++i) {
float scaledIndex = i * factor;
int floorIndex = (int)(scaledIndex);
float alpha = scaledIndex - floorIndex;
float rev_alpha = (float) (1.0 - alpha);
floorIndex = (floorIndex << 2); // x4
int nextIndex = floorIndex + 4;
// left channel: floor sample
short left = in[floorIndex + 1]; // Swap for little endian
left <<= 8;
short tmp = (short) (in[floorIndex] & 0xff);
left |= tmp;
// left channel: next sample
int nIndex = nextIndex;
short leftNext = in[nIndex + 1]; // Swap for little endian
leftNext <<= 8;
tmp = (short) (in[nIndex] & 0xff);
leftNext |= tmp;
short resampleValue = (short) (left * rev_alpha + leftNext * alpha);
byte leftLSB = (byte) (short) (resampleValue >> 8);
byte leftMSB = (byte) ((resampleValue & 0x00ff));
// right channel: floor sample
short right = in[floorIndex + 3];
right <<= 8;
tmp = (short) (in[floorIndex + 2] & 0xff);
right |= tmp;
// right channel: next sample
short rightNext = in[nIndex + 3];
rightNext <<= 8;
tmp = (short) (in[nIndex + 2] & 0xff);
rightNext |= tmp;
resampleValue = (short) (right * rev_alpha + rightNext * alpha);
byte rightLSB = (byte) (short) (resampleValue >> 8);
byte rightMSB = (byte) ((resampleValue & 0x00ff));
int outIndex = (i << 2); // i * 4
int base = outIndex;
out[base] = leftMSB; out[base + 1] = leftLSB;
out[base + 2] = rightMSB; out[base + 3] = rightLSB;
ouputSampleCount++;
}
return ouputSampleCount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment