Domanda

I have a byte array which contains pure sound data. I want to convert it to integer. bit per sample is 16. frame rate is 44100. but how to convert it into an integer?

È stato utile?

Soluzione

Just to clearify: You have a byte[] that contains pairs of byte's to form an integer? So like this: {int1B1, int1B2, int2B1, int2B2, int3B1, int3B2, ...}?

If so, you can assemble them to integers like this:

int[] audio = new int[byteArray.length/2];
for (int i = 0; i < byteArray.length/2; i++) { // read in the samples
  int lsb = byteArray[i * 2 + 0] & 0xFF; // "least significant byte"
  int msb = byteArray[i * 2 + 1] & 0xFF; // "most significant byte"
  audio[i] = (msb << 8) + lsb;
}

Of course you can optimize that loop to a single line loop, but I prefer it that way for better readability. Also, depending on the endianness of the data, you can switch ub1 and ub2.

Altri suggerimenti

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value += ((long) by[i] & 0xffL) << (8 * i);
}

you can also create a sting and use the Integer valueOf or Integer constructor

Try to use this inside a for loop. It worked for me (signed 16 bit samples, little endian).

//16 bit, litte endian (the first is the least significant)
int LSB=(int)b[i*2] & 0xff;
int MSB=(int)b[1+i*2] & 0xff;

x[i]=((MSB<<8)+LSB);
if((b[i*2+1)]&0x80)!=0)//Check the sign
       x[i]=-(65536-x[i]);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top