且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用c ++从mp4中提取音频到mp3(不使用args执行ffmpeg)

更新时间:2023-01-25 16:32:09

你可以尝试使用ffmpeg在c或c ++中做。这是正常的步骤流程。


  1. Init ffmpeg using av_register_all();


  2. 使用avformat_open_input(& informat,sourcefile,0,0)打开输入文件。


  3. 使用avformat_find_stream_info


  4. 。通过流式传输,比较codec_type和AVMEDIA_TYPE_AUDIO,找到音频流。
  5. 输入音频流后,您可以找到音频解码器并打开解码器。使用avcodec_find_decoder(in_aud_strm-> codec-> codec_id)和avcodec_open2(in_aud_codec_ctx,in_aud_codec,NULL)。


  6. 现在对于输出文件使用av_guess_format ,(const char *)outfile,NULL)。
  7. 为outformat分配上下文。


  8. 使用avcodec_find_encoder(outfmt-> audio_codec)查找输出音频编码器。


  9. 填充输出编解码器上下文与所需的采样率,样本fmt, li>
  10. 使用avio_open()打开输出文件。


  11. 使用avformat_write_header(outformat,NULL)


  12. 现在,在while循环开始读取数据包时,仅解码音频数据包,并将它们写入打开的输出文件。您可以使用av_read_frame(informat,& pkt),avcodec_decode_audio4(in_aud_codec_ctx,pframeT,& got_vid_pkt,& pkt),avcodec_encode_audio2()和av_write_frame()。


  13. 最后使用av_write_trailer写入预告片。


您可以查看ffmpeg中提供的demuxing.c和muxing.c


how can i programmatically convert ( extract the audio channel ) from mp4 video file format ?
i just can't find any thing in the web , for using c++ .
i what to dynamically link external engine that i can via c++ take mp4 file and convert it to mp3 file.
and not passing command line args to LAME or MPLAYER or FFMPEG ?

You can try using ffmpeg to do it in c or c++. Here is the normal flow of steps.

  1. Init ffmpeg using av_register_all();

  2. Open input file using avformat_open_input( &informat, sourcefile, 0, 0)).

  3. Find stream info using avformat_find_stream_info(informat, 0)).

  4. Find the audio stream by iterating through streams and comparing codec_type to AVMEDIA_TYPE_AUDIO.

  5. Once you have input audio stream you can find audio decoder and open the decoder. Use avcodec_find_decoder(in_aud_strm->codec->codec_id) and avcodec_open2(in_aud_codec_ctx, in_aud_codec, NULL).

  6. Now for output file guess the outformat using av_guess_format(NULL, (const char*)outfile, NULL).

  7. Allocate context for outformat.

  8. Find output audio encoder using avcodec_find_encoder(outfmt->audio_codec).

  9. Add new stream audio stream avformat_new_stream(outformat, out_aud_codec).

  10. Fill output codec context with desired sample rate, sample fmt, channel etc.

  11. Open output file using avio_open().

  12. Write the output headers using avformat_write_header(outformat, NULL).

  13. Now in while loop start reading packet, decode only audio packet encode them and write them in opened output file. You can use av_read_frame(informat, &pkt) , avcodec_decode_audio4(in_aud_codec_ctx, pframeT, &got_vid_pkt, &pkt), avcodec_encode_audio2() and av_write_frame().

  14. Finally write trailer using av_write_trailer.

You can looking into demuxing.c and muxing.c provided in ffmpeg examples.