[英]Extract audio to mp3 from mp4 using C++ (not executing ffmpeg with args)
如何以編程方式從 mp4 視頻文件格式轉換(提取音頻通道)?
我在網上找不到任何關於使用 C++ 的東西。
將命令行參數傳遞給 LAME 或 MPLAYER 或 FFMPEG 不是一種選擇。
您可以嘗試使用 ffmpeg 在 C 或 C++ 中執行此操作。 這是正常的步驟流程。
使用 av_register_all() 初始化 ffmpeg;
使用 avformat_open_input( &informat, sourcefile, 0, 0)) 打開輸入文件。
使用 avformat_find_stream_info(informat, 0)) 查找流信息。
通過遍歷流並將 codec_type 與 AVMEDIA_TYPE_AUDIO 進行比較來查找音頻流。
輸入音頻流后,您可以找到音頻解碼器並打開解碼器。 使用 avcodec_find_decoder(in_aud_strm->codec->codec_id) 和 avcodec_open2(in_aud_codec_ctx, in_aud_codec, NULL)。
現在對於輸出文件,使用 av_guess_format(NULL, (const char*)outfile, NULL) 猜測輸出格式。
為輸出格式分配上下文。
使用 avcodec_find_encoder(outfmt->audio_codec) 查找輸出音頻編碼器。
添加新的流音頻流 avformat_new_stream(outformat, out_aud_codec)。
使用所需的采樣率、采樣頻率、通道等填充輸出編解碼器上下文。
使用 avio_open() 打開輸出文件。
使用 avformat_write_header(outformat, NULL) 寫入輸出標頭。
現在在while循環中開始讀取數據包,僅解碼音頻數據包對它們進行編碼並將它們寫入打開的輸出文件中。 您可以使用 av_read_frame(informat, &pkt) , avcodec_decode_audio4(in_aud_codec_ctx, pframeT, &got_vid_pkt, &pkt), avcodec_encode_audio2() 和 av_write_frame()。
最后使用 av_write_trailer 編寫預告片。
您可以查看 ffmpeg 示例中提供的 demuxing.c 和 muxing.c。
從transcode_aac官方示例開始。 我們只需要很少的改動:
在文件范圍內添加一個全局變量:
/* The index of audio stream that will be transcoded */ static int audio_stream_idx = -1;
在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; }
在第181行,將硬編碼的編解碼器 ID AV_CODEC_ID_AAC
為
(*output_format_context)->oformat->audio_codec
在第182行,替換錯誤消息:
fprintf(stderr, "Could not find audio encoder for %s(%d).\\n", (*output_format_context)->oformat->long_name, (*output_format_context)->oformat->audio_codec);
在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.