I am using LAME on my Android App in order to convert PCM data from AudioRecoder to MP3. I can generate the MP3 file, but it has some noise.
This is my partial jni code:
jbyte *bufferArray = (*env)->GetByteArrayElements(env, buffer, NULL);
//Convert To Short
int shortLength = length / 2;
short int shortBufferArray[shortLength];
int i ;
for(i=0;i<shortLength;i++){
int index = 2*i;
shortBufferArray[i] = (bufferArray[index+1] << 8) | bufferArray[index];
}
int mp3BufferSize = (int)(shortLength*1.5+7200);
unsigned char output[mp3BufferSize];
int encodeResult;
if(lame_get_num_channels(lame)==2){
encodeResult = lame_encode_buffer_interleaved(lame, shortBufferArray, shortLength/2, output, mp3BufferSize);
}else{
encodeResult = lame_encode_buffer(lame, shortBufferArray, shortBufferArray, shortLength, output, mp3BufferSize);
}
if(encodeResult < 0){
return NULL;
}
jbyteArray result = (*env)->NewByteArray(env, encodeResult);
(*env)->SetByteArrayRegion(env, result, 0, encodeResult, output);
(*env)->ReleaseByteArrayElements(env, buffer, bufferArray, 0);
return result;
I call this jni function to encode PCM data to MP3 data, and than I write MP3 data to file to build a MP3 file. After PCM data is all encoded, the MP3 file is generated. It seems that play the MP3 file is normal, but the MP3 file has poor quality even if I use 320kbps as its bitrate. There are some noise in the MP3 file, but why?
shortBufferArray[i] = (bufferArray[index+1] << 8) | bufferArray[index];
Will introduce errors when the less significant byte is implicitly (and for your purposes, improperly) sign extended to a short.
Instead, use
shortBufferArray[i] = (bufferArray[index+1] << 8) | ((unsigned char) bufferArray[index]);
to force it to treat the lower byte as not having a sign bit (only the upper byte does).