网上很多关于lame使用教程的代码几乎都是在使用lame_encode_flush后就结束了编码工作,虽然编码后的文件能播放,但是音频显示时长已经错误了,这会引起前进后退等操作出现问题。
使用官方的lame.exe去编码就不会有问题,我于是翻了下官方的命令行程序源码,发现在编码结尾后会调用lame_get_lametag_frame来获取一个帧数据并写入到第一帧中去。
/*
* OPTIONAL:
* lame_get_lametag_frame copies the final LAME-tag into 'buffer'.
* The function returns the number of bytes copied into buffer, or
* the required buffer size, if the provided buffer is too small.
* Function failed, if the return value is larger than 'size'!
* Make sure lame_encode flush has been called before calling this function.
* NOTE:
* if VBR tags are turned off by the user, or turned off by LAME,
* this call does nothing and returns 0.
* NOTE:
* LAME inserted an empty frame in the beginning of mp3 audio data,
* which you have to replace by the final LAME-tag frame after encoding.
* In case there is no ID3v2 tag, usually this frame will be the very first
* data in your mp3 file. If you put some other leading data into your
* file, you'll have to do some bookkeeping about where to write this buffer.
*/
size_t CDECL lame_get_lametag_frame(const lame_global_flags *, unsigned char* buffer, size_t size);
注释最后几行说了,lame默认会在mp3开头插入一个空帧(称为XING Frame),所以我们应该在lame_encode_flush操作结束后调用lame_get_lametag_frame来取得XING Frame的数据并写入到第一帧中,这样mp3的时长才是正确的。
lame也提供了lame_set_bWriteVbrTag函数来关闭插入头帧的行为,但几乎用不上。另外还有一个相关的函数lame_mp3_tags_fid。
参考资料:
http://blog.csdn.net/iteye_7030/article/details/82450005
http://gabriel.mp3-tech.org/mp3infotag.html