Android : Converting Short array from Audio Record to Byte array without degrading audio quality?

on Wednesday, July 9, 2014


I'm recording audio using the Android Audio Record class. The recording is PCM 16bit so (I heard) it is best to let Audio Record write the data into a Short array. However for what I'm trying to do I need to convert the Short array into a byte array. I have tried a few methods but all of them degrades the quality of the audio in different ways.


I frist tried:



byte[] bytes2 = new byte[shortsA.length * 2];
ByteBuffer.wrap(bytes2).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(shortsA);


but the result is very quiet and choppy audio.


The second method I tried is:



byte[] MyShortToByte(short[] buffer) {
int N = buffer.length;
float f[] = new float[N];
float min = 0.0f;
float max = 0.0f;
for (int i=0; i<N; i++) {
f[i] = (float)(buffer[i]);
if (f[i] > max) max = f[i];
if (f[i] < min) min = f[i];
}
float scaling = 1.0f+(max-min)/256.0f; // +1 ensures we stay within range and guarantee no divide by zero if sequence is pure silence ...

ByteBuffer byteBuf = ByteBuffer.allocate(N);
for (int i=0; i<N; i++) {
byte b = (byte)(f[i]/scaling); /*convert to byte. */
byteBuf.put(b);
}
return byteBuf.array();
}


from http://stackoverflow.com/a/15188181/902631 but the result is sped up and high-pitched audio, like the original audio was fast-forwarded at 2x speed. However the volume is higher than the first one and it's not choppy.


Are there any external libraries that I can use or any audio-specific conversion methods that don't degrade the quality of the audio?


Any help would be appreciated!


0 comments:

Post a Comment