使用c++将音频从mp4提取为mp3(不使用参数执行ffmpeg)

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

本文关键字:参数 执行 ffmpeg mp3 音频 c++ mp4 提取 使用      更新时间:2023-10-16

如何以编程方式转换(提取音频通道)从mp4视频文件格式?
我只是在网上找不到任何东西,使用c++。

将命令行参数传递给LAME或MPLAYER或FFMPEG不是一个选项。

您可以尝试在C或c++中使用ffmpeg来完成。以下是正常的步骤流程。

    使用av_register_all() Init ffmpeg;
  1. 使用avformat_open_input(&info, sourcefile, 0, 0))打开输入文件

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

  3. 通过遍历流并将codec_type与AVMEDIA_TYPE_AUDIO进行比较来查找音频流。

  4. 一旦你有输入音频流,你可以找到音频解码器并打开解码器。使用avcodec_find_decoder(in_aud_strm->codec->codec_id)和avcodec_open2(in_aud_codec_ctx, in_aud_codec, NULL)

  5. 现在使用av_guess_format(NULL, (const char*)outfile, NULL)猜测输出文件的输出格式

  6. 为输出格式分配上下文。

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

  8. 添加新的音频流avformat_new_stream(outformat, out_aud_codec)

  9. 用期望的采样率,采样fmt,通道等填充输出编解码器上下文

  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。

从transcode_aac官方示例开始。我们只需要很少的改动:

  1. 在文件范围内添加全局变量:

    /* The index of audio stream that will be transcoded */
    static int audio_stream_idx = -1;
    
  2. open_input_file()中的
  3. ,将第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 streamn");
        avformat_close_input(input_format_context);
        return AVERROR_EXIT;
    }
    
  4. 在第92和107行,用streams[audio_stream_idx]代替streams[0]

  5. 在第181行,将硬编码编解码器ID AV_CODEC_ID_AAC替换为

    (*output_format_context)->oformat->audio_codec
    
  6. 在第182行,替换错误信息:

    fprintf(stderr, "Could not find audio encoder for %s(%d).n", (*output_format_context)->oformat->long_name, (*output_format_context)->oformat->audio_codec);
    
  7. 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这是文件,适用于android。