0

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 https://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!

Community
  • 1
  • 1
kevdliu
  • 1,709
  • 4
  • 29
  • 46

2 Answers2

1

Why don't you try this, While read data from AudioRecord object, read it into byte[] array instead of short array

audioRecord.startRecording();
byte[] buffer = new byte[_bufferSize]; //recorded data is stored in this byte array
audioRecord.read(buffer, 0, _bufferSize);
Venkat
  • 64
  • 4
0

First off, you cannot change the bit depth of your audio without degrading the quality.I'm really not sure how you are doing your scaling.Look at the following indicative code to get an idea about how bit reduction can be done.

float byteNorm = Absolute(Byte.MaxValue);  //255
float shortNorm = Absolute(Short.MinValue); //32768

for (int audioSample = 0; audioSample < numShorts; audioSample++)
{
    myActualSample = (float)myShorts[audioSample] / shortNorm;
    myBytes[audioSample] = (byte)(mySample * byteNorm);
}
KillaKem
  • 995
  • 1
  • 13
  • 29