此代码适用于其他的平台,纯C语言,不使用第三方库
解码:
#include <stdio.h>
short 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);
}
int g711_decode(char* pRawData, const char* pBuffer, int nBufferSize)
{
int i;
short tmp[1024];
for(i=0; i<nBufferSize; i++)
{
tmp[i] = decode(pBuffer[i]);
pRawData[i*2] = tmp[i]&0xff;
pRawData[i*2+1] = tmp[i]>>8;
}
return nBufferSize*2;
}
void main(void)
{
FILE *InFile= NULL, *OutFile= NULL;
char g711_Buffer[1024];
char pcmBuffer[2048];
int pcmbufsize;
unsigned int len = 0;
char OutFileName[] = "../song.pcm";
char InFileName [] = "../song.bit";
InFile = fopen(InFileName, "rb+");
if(InFile == NULL)
{
printf("Error opening input file %s\n", InFileName);
}
OutFile = fopen (OutFileName, "wb+");
if (OutFile == NULL)
{
printf("Error opening output file %s\n", OutFileName);
}
while((len = fread(g711_Buffer, 1, 1024, InFile)) > 0){
pcmbufsize = g711_decode(pcmBuffer, g711_Buffer, len);
fwrite(pcmBuffer, 1, pcmbufsize, OutFile);
}
if(InFile)
{
fclose(InFile);
}
if(OutFile)
{
fclose(OutFile);
}
for(;;)
{
}
}
编码:
#include <stdio.h>
#define MAX 32635
unsigned char 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);
}
int g711_encode( char* pCodecBits, const char* pBuffer, int nBufferSize)
{
int i;
short tmp[512];
for(i=0; i<nBufferSize/2; i++)
{
tmp[i] = (pBuffer[i*2+1]<<8) + pBuffer[i*2];
pCodecBits[i] = encode(tmp[i]);
}
return nBufferSize/2;
}
void main(void)
{
/*打开文件*/
FILE *InFile= NULL, *OutFile= NULL;
char g711_Buffer[1024];
char pcmBuffer[1024];
int pcmbufsize;
unsigned int len = 0;
char OutFileName[] = "../song.bit";
char InFileName [] = "../song.pcm";
InFile = fopen(InFileName, "rb+");
if(InFile == NULL)
{
printf("Error opening input file %s\n", InFileName);
}
OutFile = fopen (OutFileName, "wb+");
if (OutFile == NULL)
{
printf("Error opening output file %s\n", OutFileName);
}
while((len = fread(pcmBuffer, 1, 1024, InFile)) > 0){
pcmbufsize = g711_encode(g711_Buffer,pcmBuffer, len);
fwrite(g711_Buffer, 1, pcmbufsize, OutFile);
}
if(InFile)
{
fclose(InFile);
}
if(OutFile)
{
fclose(OutFile);
}
for(;;)
{
}
}
参考博客:G711编解码(G711与PCM类型互转)_qq_24551315的博客-CSDN博客_g711解码pcm
若有其他的问题,可以添加一下我们的群:657407920,希望有更多大家加入,一起讨论技术!