以下程序用在16Khz的单声道或者8Khz的双声道的pcm数据的音量计算.
来源自搜索的各种资料加实际测试.
参考源暂未统计出.
注意要求的对数函数是log10,不是log.
int pcm_db_count(const unsigned char* ptr, size_t size)
{
int ndb = 0;
short int value;
int i;
long v = 0;
for(i=0; i<size; i+=2)
{
memcpy((char*)&value, ptr+i, 1);
memcpy((char*)&value+1, ptr+i+1, 1);
v += abs(value);
}
v = v/(size/2);
if(v != 0) {
ndb = (int)(20.0*log10((double)v / 65535.0 ));
}
else {
ndb = -96;
}
return ndb;
}
实际工程中用的代码:
int CalcLoudNess(char * pData,int length,int soundwidth )
{
int ndb = 0,i;
long v = 0;
if(soundwidth == 16){
short int value;
assert(sizeof(short int) == 2 );
for(i = 0;i < length;i += 2)
{
*(char *)&value = *(pData + i);
*((char *)&value + 1) = *(pData + i + 1);
v += abs(value);
}
v = v / ( length /2) ;
if(v != 0){
ndb = (int)(20.0 * log10((double)v / 65535.0 ) );
}else{
ndb = -96;
}
return ndb;
}else if(soundwidth == 32) {
/// TODO 32 位音频数据
}
}