簡體   English   中英

使用 C++ 從 mp4 中提取音頻到 mp3(不使用 args 執行 ffmpeg)

[英]Extract audio to mp3 from mp4 using C++ (not executing ffmpeg with args)

如何以編程方式從 mp4 視頻文件格式轉換(提取音頻通道)?
我在網上找不到任何關於使用 C++ 的東西。

將命令行參數傳遞給 LAME 或 MPLAYER 或 FFMPEG 不是一種選擇。

您可以嘗試使用 ffmpeg 在 C 或 C++ 中執行此操作。 這是正常的步驟流程。

  1. 使用 av_register_all() 初始化 ffmpeg;

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

  3. 使用 avformat_find_stream_info(informat, 0)) 查找流信息。

  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(NULL, (const char*)outfile, NULL) 猜測輸出格式。

  7. 為輸出格式分配上下文。

  8. 使用 avcodec_find_encoder(outfmt->audio_codec) 查找輸出音頻編碼器。

  9. 添加新的流音頻流 avformat_new_stream(outformat, out_aud_codec)。

  10. 使用所需的采樣率、采樣頻率、通道等填充輸出編解碼器上下文。

  11. 使用 avio_open() 打開輸出文件。

  12. 使用 avformat_write_header(outformat, NULL) 寫入輸出標頭。

  13. 現在在while循環中開始讀取數據包,僅解碼音頻數據包對它們進行編碼並將它們寫入打開的輸出文件中。 您可以使用 av_read_frame(informat, &pkt) , avcodec_decode_audio4(in_aud_codec_ctx, pframeT, &got_vid_pkt, &pkt), avcodec_encode_audio2() 和 av_write_frame()。

  14. 最后使用 av_write_trailer 編寫預告片。

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

transcode_aac官方示例開始。 我們只需要很少的改動:

  1. 在文件范圍內添加一個全局變量:

     /* The index of audio stream that will be transcoded */ static int audio_stream_idx = -1;
  2. open_input_file() ,將第83-88行替換為

    for (audio_stream_idx = 0; audio_stream_idx < (*input_format_context)->nb_streams; audio_stream_idx++) { if ((*input_format_context)->streams[audio_stream_idx]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) break; } if (audio_stream_idx >= (*input_format_context)->nb_streams) { fprintf(stderr, "Could not find an audio stream\\n"); avformat_close_input(input_format_context); return AVERROR_EXIT; }
  3. 在第92行和第107 行,將streams[0]替換為streams[audio_stream_idx]

  4. 在第181行,將硬編碼的編解碼器 ID AV_CODEC_ID_AAC

    (*output_format_context)->oformat->audio_codec
  5. 在第182行,替換錯誤消息:

     fprintf(stderr, "Could not find audio encoder for %s(%d).\\n", (*output_format_context)->oformat->long_name, (*output_format_context)->oformat->audio_codec);
  6. decode_audio_frame()我們跳過非音頻幀:在第389行,寫

    if (error != AVERROR_EOF && input_packet.stream_index != audio_stream_idx) goto cleanup;

PS請注意,當音頻流不需要轉碼時,此解決方案無法以最佳方式處理這種情況。 大多數mp4文件都有 AAC 或 AC3 音軌,因此請確保使用相關解碼器和 MP3 編碼器(例如Shine )構建 ffmpeg。

這里PPS文件,適用於 Adnroid。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM