wav格式音訊檔案轉換為Mp3格式
阿新 • • 發佈:2019-02-08
1.編譯lame(我用的lame-3.99.5)庫 編譯後會生成相應的lame動態庫
編譯步驟:
(1)進到原始碼目錄,找到configure檔案,在命令列執行./configure (-h)帶引數可以檢視編譯的資訊
(2)make
(3)make install
2.將編譯好的動態庫放到預設(程式預設查詢路徑)的路徑下 編譯好的檔案在/usr/local/lib目錄下
3.在QT工程的.pro檔案中新增lame動態庫
LIBS +=-L ./ -lmp3lame
4.將lame.h標頭檔案包含到工程中 就可以呼叫相應的lame介面了
#include <lame.h>
程式碼實現部分
bool RecordConvertObject::WavToMp3(QString sWavFilePath,QString sMp3FilePath,float &fCostSeconds,QString &sError)
sError="";
fCostSeconds=0.00;
if ((sWavFilePath.isEmpty()) || (sMp3FilePath.isEmpty()))
{
sError=tr("路徑引數無效");
return false;
}
//2..
QDateTime dtBegin=QDateTime::currentDateTime();
FILE *pcm = fopen(sWavFilePath.toLocal8Bit().data(), "rb");
if(pcm==NULL)
{
sError = QObject::tr("無法開啟wav檔案(%1)").arg(sWavFilePath);
return false;
}
FILE *mp3 = fopen(sMp3FilePath.toLocal8Bit().data(), "wb+");
if(mp3==NULL)
{
fclose(pcm);
sError = QObject::tr("建立mp3檔案(%1)失敗").arg(sMp3FilePath);
return false;
}
//3..
qDebug()<<"wav convert begin";
int read, write,i=0;
const int PCM_SIZE = 8192;
const int MP3_SIZE = 8192;
short int pcm_buffer[PCM_SIZE*2];
unsigned char mp3_buffer[MP3_SIZE];
lame_t lame = lame_init();
lame_set_num_channels(lame, 1); //1=單聲道
lame_set_in_samplerate(lame, 24000); //24000
lame_set_brate(lame, 64); //壓縮的位元率為128K
lame_set_mode(lame, MONO); //MONO
lame_set_quality(lame, 5); //2
lame_set_copyright(lame,1); //1
lame_set_original(lame,1); //1
//vbr setting
if (bConvertAsCBR)
lame_set_VBR(lame, vbr_off);
else
{
lame_set_VBR_q(lame,9); //9
lame_set_VBR(lame, vbr_default); //vbr_default
lame_set_bWriteVbrTag(lame,1);
lame_set_VBR_max_bitrate_kbps(lame,192);
lame_set_VBR_quality(lame,5);
}
//init lame param;
int iInitResult= lame_init_params(lame);
if (iInitResult<0)
{
sError="init lame param fail:"+QString::number(iInitResult);
lame_close(lame);
fclose(mp3);
fclose(pcm);
return false;
}
//convert begin;
int iTemp=0;
int iTotal=0;
do {
iTemp++;
if((iTemp!=0)&&(iTemp%5==0))
{
usleep(20000);
iTemp=0;
iTotal++;
}
read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
if (read == 0)
write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
else
write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
fwrite(mp3_buffer, write, 1, mp3);
} while (read != 0);
lame_mp3_tags_fid(lame,mp3); //only for vbr;
lame_close(lame);
fclose(mp3);
fclose(pcm);
//4..
qDebug()<<"wav convert finish";
fCostSeconds=dtBegin.msecsTo(QDateTime::currentDateTime()) /1000.0;
qDebug()<<"cost time(s):"<<fCostSeconds;
return true;
}