FFmpeg - 音频解码过程

来源:互联网 发布:高洛峰php视频 编辑:程序博客网 时间:2024/05/01 18:23

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);

1 0
原创粉丝点击