http://blog.csdn.net/rightorwrong/article/details/4209467
搞语音对讲几天了,播放时声音干扰太大了。拖得时间久有两个原因:
1.每次采样的位数这个值设置的问题。本来是用的采样位数为16,但是服务端那边说用8。导致编解码时8位的始终有杂音。
1.G711编解码的问题:用了一个错误的编解码程序。目前用的编解码代码对于8为始终有杂音
下面把编解码的代码放在这里,16为采集效果很好
- //编码
- int CG711Decoder::G711_EnCode(unsigned char* pCodecBits, const char* pBuffer, int nBufferSize)
- {
- short* buffer = (short*)pBuffer;
- for(int i=0; i<nBufferSize/2; i++)
- {
- pCodecBits[i] = encode(buffer[i]);
- }
- return nBufferSize/2;
- }
- //解码
- int CG711Decoder::G711_Decode(char* pRawData, const unsigned char* pBuffer, int nBufferSize)
- {
- short *out_data = (short*)pRawData;
- for(int i=0; i<nBufferSize; i++)
- {
- out_data[i] = decode(pBuffer[i]);
- }
- return nBufferSize*2;
- }
- #define MAX (32635)
- unsigned char CG711Decoder::encode(short pcm)
- {
- int sign = (pcm & 0x8000) >> 8;
- if (sign != 0)
- pcm = -pcm;
- if (pcm > MAX) pcm = MAX;
- int exponent = 7;
- int expMask;
- for (expMask = 0x4000; (pcm & expMask) == 0
- && exponent>0; exponent--, expMask >>= 1) { }
- int mantissa = (pcm >> ((exponent == 0) ? 4 : (exponent + 3))) & 0x0f;
- unsigned char alaw = (unsigned char)(sign | exponent << 4 | mantissa);
- return (unsigned char)(alaw^0xD5);
- }
- short CG711Decoder::decode(unsigned char alaw)
- {
- alaw ^= 0xD5;
- int sign = alaw & 0x80;
- int exponent = (alaw & 0x70) >> 4;
- int data = alaw & 0x0f;
- data <<= 4;
- data += 8;
- if (exponent != 0)
- data += 0x100;
- if (exponent > 1)
- data <<= (exponent - 1);
- return (short)(sign == 0 ? data : -data);
- }