1、何为LAME
LAME 是最好的MP3编码器,编码高品质MP3的最好也是唯一的选择,是目前最好的MP3编码引擎。LAME编码出来的MP3音色纯厚、空间宽广、低音清晰、细节表现良好,它独创的心理音响模型技术保证了CD音频还原的真实性,配合VBR和ABR参数,音质几乎可以媲美CD音频,但文件体积却非常小。对于一个免费引擎,LAME的优势不言而喻。
2、LAME的三种编码方式
VBR(Variable Bitrate)动态比特率。也就是没有固定的比特率,压缩软件在压缩时根据音频数据即时确定使用什么比特率,这是以质量为前提兼顾文件大小的方式,推荐编码模式;
ABR(Average Bitrate)平均比特率,是VBR的一种插值参数。LAME针对CBR不佳的文件体积比和VBR生成文件大小不定的特点独创了这种编码模式。ABR在指定的文件大小内,以每50帧(30帧约1秒)为一段,低频和不敏感频率使用相对低的流量,高频和大动态表现时使用高流量,可以做为VBR和CBR的一种折衷选择。
CBR(Constant Bitrate),常数比特率,指文件从头到尾都是一种位速率。相对于VBR和ABR来讲,它压缩出来的文件体积很大,而且音质相对于VBR和ABR不会有明显的提高。
3、使用LAME对wav文件进行编码
在vs环境下的配置就不说了,很简单,主要介绍代码:
#include "stdafx.h" #include "lame.h" #include <stdlib.h> #define INBUFSIZE 4096 #define MP3BUFSIZE (int) (1.25 * INBUFSIZE) + 7200 int encode(char * inPath, char * outPath) { int status = 0; lame_global_flags * gfp = NULL; int ret_code = 0; FILE * infp = NULL; FILE * outfp = NULL; short * input_buffer = NULL; int input_samples = 0; unsigned char * mp3_buffer = NULL; int mp3_bytes = 0;
gfp = lame_init(); //初始化编码器,设置编码器的默认参数,成功返回指向一个全局的结构体指针,失败返回NULL
if (gfp == NULL) { printf("lame_init failed/n"); status = -1; goto exit; } ret_code = lame_init_params(gfp); //根据得到的gfp配置其他组件,成功返回0,失败返回-1
if (ret_code < 0) { printf("lame_init_params returned %d/n",ret_code); status = -1; goto close_lame; } infp = fopen(inPath, "rb"); //打开要编码的wav文件
outfp = fopen(outPath, "wb"); //打开要生成的mp3文件
input_buffer = (short*)malloc(INBUFSIZE*2); //为读取wav文件内容申请缓存
mp3_buffer = (unsigned char*)malloc(MP3BUFSIZE); //为编码的MP3文件内容申请缓存
do { input_samples = fread(input_buffer, 2, INBUFSIZE, infp);
//这个函数是编码左右声道数据交替的函数,返回编码数据的长度
mp3_bytes = lame_encode_buffer_interleaved(gfp, input_buffer,input_samples/2, mp3_buffer, MP3BUFSIZE); if (mp3_bytes < 0) { printf("lame_encode_buffer_interleaved returned %d/n", mp3_bytes); status = -1; goto free_buffers; } else if(mp3_bytes > 0) { fwrite(mp3_buffer, 1, mp3_bytes, outfp); } }while (input_samples == INBUFSIZE);
mp3_bytes = lame_encode_flush(gfp, mp3_buffer, sizeof(mp3_buffer)); if (mp3_bytes > 0) { printf("writing %d mp3 bytes/n", mp3_bytes); fwrite(mp3_buffer, 1, mp3_bytes, outfp); } free_buffers: free(mp3_buffer); free(input_buffer); fclose(outfp); fclose(infp); close_lame:
//释放所有内存
lame_close(gfp); exit: return status; } int _tmain(int argc, char * argv[]) { if (argc < 3) { printf("usage: lame_test rawinfile mp3outfile/n"); } encode(/*argv[1]*/"cunzai.wav", /*argv[2]*/"cunzai.mp3"); return 0; }
4、总结大家可以在编码过程中使用lame.h文件中的接口设置各种参数,具体大家自己去尝试吧