Reputation: 241
I have converted byte[]
into float[]
using this way:
public voidcheckingActivity(byte[] data, int numbytes) {
size_data_proc = data.length / 2;
float[] data_proc = new float[size_data_proc];
for (int i = 0; i < data.length; i += 2) {
data_proc[i / 2] = data[i] | (data[i + 1] << 8);
}
}
Because I am reading audio sample 16 bits.
Now I need the inverse process: I have a float[]
which contains 16 bits samples and I want to convert in byte[]
.
So, I suppose that I have to create a byte[]
that size is float*2
but how can I obtain the value of byte
s ?
thanks
EDIT:
To be more preccis, i capture blocks of 200 ms of 16 bits audio. to process these blocks i need samples in float, so i have to combine 2 bytes of byte array in one element of float. This process is code below.
And after process i need reconvert my float samples in bytes, so i need that each elements of float[] is in two elemets of byte[]
Upvotes: 0
Views: 1077
Reputation: 3984
Audio data in Android is typically little endian 16-bit signed PCM. I think you may have the byte order reversed (but it's been a while). Also, if you don't mask off the least significant byte you will get spurious audio artifacts because of automatic sign extension.
With fixes for those, your code should probably look something like this:
public void checkingActivity(byte[] data {
float[] data_proc = new float[size_data_proc];
for (int i = 0; i < data.length; i += 2) {
data_proc[i / 2] = (int) (data[i] << 8) | (int) (data[i+1] & 0x00ff);
}
}
The inverse operation then looks like:
public byte[] floatArrayToBytes(float[] data {
byte[] bytes = new byte[data.length * 2];
float scale = 1.0f;
int ix = 0;
for (float sample: data) {
int value = sample * scale;
bytes[ix++] = (byte) ((value >> 8) & 0x00ff);
bytes[ix++] = (byte) (value & 0x00ff);
}
return bytes;
}
You might want to normalise your audio to a range of -1.0f to +1.0f if you're working with float values.
Upvotes: 2
Reputation: 1861
You can use java.nio.ByteBuffer
class :
public static byte[] float2ByteArray(final float[] value) {
ByteBuffer buffer = ByteBuffer.allocate(4 * value.length);// a float has 4 bytes
for (float f : value) {
buffer.putFloat(f);
}
return buffer.array();
}
Upvotes: 0