FFmpeg - 音頻解碼過程
1. 注冊所有解碼器
av_register_all();
2. Codec & CodecContext
AVCodec* codec = avcodec_find_decoder(CODEC_ID_AAC);
if (!codec)
{
fprintf(stderr, "codec not found\n");
exit(1);
}
AVCodecContext *codec_ctx= avcodec_alloc_context();
if (avcodec_open(codec_ctx, codec) < 0)
{
fprintf(stderr, "could not open codec\n");
exit(1);
}
3. 準備好AVPacket
AVPacket avpkt;
av_init_packet(&avpkt);
avpkt.size = pesdec.m_nEsLength;
avpkt.data = pesdec.m_pEs;
avpkt.pts = pesdec.m_nPts;
4. 準備好一個足夠大的output buffer,用于存儲音頻解碼得到的數據
奇怪的是長度要為AVCODEC_MAX_AUDIO_FRAME_SIZE *2,少了還不行(aac音頻時,會crash)
int16_t * outbuf = new int16_t[AVCODEC_MAX_AUDIO_FRAME_SIZE * 2];
5. 解碼
while(1)
{
// 讀取一個完整的PES
// 解碼
while (avpkt.size > 0)
{
int out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE; // 對于AAC解碼器來說,長度不能小于這個
int len = avcodec_decode_audio3(codec_ctx, (short *)outbuf, &out_size, &avpkt);
if (len <= 0)
{
fprintf(stderr, "Error while decoding\n");
break;
}
if (out_size > 0)
{
double pts = (double) avpkt.pts / 45000;
printf("[time: %.3f] sound sample \n", pts);
// fwrite(outbuf, 1, out_size, outfile);
// printf("get %d bytes.\n", out_size);
}
avpkt.size -= len;
avpkt.data += len;
}
}
6. 釋放資源
delete [] outbuf;
avcodec_close(codec_ctx);
av_free(codec_ctx);