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);
}