2,543
社区成员
发帖
与我相关
我的任务
分享
// Register all formats and codecs
av_register_all();
avcodec_register_all();
//av_log_set_callback(log_callback);
USES_CONVERSION;
string strSrcFile = P2P_W2A(pFileData->strInputFile);
pFormatCtxDec = avformat_alloc_context();
if (NULL == pFormatCtxDec)
{
return;
}
// Open video file
#define av_open_input_file avformat_open_input
if(av_open_input_file(&pFormatCtxDec, strSrcFile.c_str(), NULL, NULL)!=0)
return ; // Couldn't open file
// Retrieve stream information
if(av_find_stream_info(pFormatCtxDec)<0)
return ; // Couldn't find stream information
for(i=0; i<pFormatCtxDec->nb_streams; i++)
{
if(pFormatCtxDec->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
{
videoStream=i;
}
else if(pFormatCtxDec->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO)
{
audioStream=i;
}
}
if (audioStream != -1)
{
pACodecCtxDec = pFormatCtxDec->streams[audioStream]->codec;
}
if (pACodecCtxDec)
{
pACodecDec=avcodec_find_decoder(pACodecCtxDec->codec_id);
}
// Open codec
BOOL bOpenAudio = FALSE;
if (pACodecCtxDec && pACodecDec)
{
if(avcodec_open2(pACodecCtxDec, pACodecDec, NULL)>=0)
{
bOpenAudio = TRUE;
}
}
pAFrameDec = avcodec_alloc_frame();
if (audioStream!=-1 && pAFrameDec == NULL)
{
return;
}
while(av_read_frame(pFormatCtxDec, &packet)>=0)
{
if (packet.stream_index==audioStream)
{
int ret = 0;
while(packet.size > 0)
{
ret = avcodec_decode_audio4(pACodecCtxDec,pAFrameDec,&got_output,&packet);//若为音频包,解码该音频包
if(got_output == 0)
{
continue;
}
int data_size = av_samples_get_buffer_size(pAFrameDec->linesize, pACodecCtxDec->channels,
pAFrameDec->nb_samples,
pACodecCtxDec->sample_fmt, 0);
int n = fwrite(pAFrameDec->data[0], 1, pAFrameDec->linesize[0], TmpAudio);
fflush(TmpAudio);
packet.size -= ret;
packet.data += ret;
}
}
////mp3 to pcm
for (int i = 0; i < data_size/2; i++)
{
data[i*2] = (char)(sample_buffer[i/2] & 0xFF);
data[i*2+1] = (char)((sample_buffer[i/2] >>8) & 0xFF);
}
fwrite(data, data_size, 1, pcm);
fflush(pcm);