PCM無符號16位小端存儲文件讀取和解析總結
假設小端存儲方式的文件中存儲了0xF3FF ,存儲的真實的數據是多少呢?真實的數據應該是-13,因爲是小端存儲方式所以
應該把高位和低位互換即0xFFF3,由於最高位爲1,所以要求補碼纔對,即0x800D,即十進制的-13。
再假設把0xF3FF讀取到內存中, 讀取到指針位置爲0x00000001中,如果cpu是小端存儲的方式,那麼高字節存儲高位,低字節存儲低位,那麼0x00000001存儲oxFF, 0x00000002存儲0xF3,這個時候存儲的數據和真實存儲的數據一樣的。都是0xFFF3。所以這時候對其進行算術運算加減乘除是沒有問題的。不需要再對其高字節和低字節互換了。
小例子,對pcm數據的音量減半
extern "C"
JNIEXPORT void JNICALL
Java_com_liuxin_audiolib_LXPlayer_testAudio(JNIEnv *env, jobject thiz, jstring source,
jstring dest) {
const char *sourceUrl = env->GetStringUTFChars(source, NULL);
const char *destUrl = env->GetStringUTFChars(dest, NULL);
FILE *fp = fopen(sourceUrl, "rb+");
FILE *fp_stat = fopen(destUrl, "wb+");
unsigned char *sample = (unsigned char *) malloc(2);
int cnt = 0;
while (!feof(fp)) {
fread(sample, 1, 2, fp);
short *sampleP= reinterpret_cast<short *>(sample);
short samplenum = (*sampleP)/2;
fwrite(sample,1,2,fp_stat);
cnt++;
}
free(sample);
fclose(fp);
fclose(fp_stat);
env->ReleaseStringUTFChars(source, sourceUrl);
env->ReleaseStringUTFChars(dest, destUrl);
}