C++;ffmpeg将音频提取到mp3(解复用) 我试图编写一个C++程序,让我从音频文件中提取音频到MP3文件。我搜索了互联网和stackoverflow,但没能让它工作

C++;ffmpeg将音频提取到mp3(解复用) 我试图编写一个C++程序,让我从音频文件中提取音频到MP3文件。我搜索了互联网和stackoverflow,但没能让它工作,c++,audio,ffmpeg,mp3,C++,Audio,Ffmpeg,Mp3,我选择的库是ffmpeg,我必须用C/C++来实现。这就是我目前所拥有的 // Step 1 - Register all formats and codecs avcodec_register_all(); av_register_all(); AVFormatContext* fmtCtx = avformat_alloc_context(); // Step 2 - Open input file, and allocate format context if(avformat_ope

我选择的库是ffmpeg,我必须用C/C++来实现。这就是我目前所拥有的

// Step 1 - Register all formats and codecs
avcodec_register_all();
av_register_all();

AVFormatContext* fmtCtx = avformat_alloc_context();

// Step 2 - Open input file, and allocate format context
if(avformat_open_input(&fmtCtx, filePath.toLocal8Bit().data(), NULL, NULL) < 0)
    qDebug() << "Error while opening " << filePath;

// Step 3 - Retrieve stream information
if(avformat_find_stream_info(fmtCtx, NULL) < 0)
    qDebug() << "Error while finding stream info";

// Step 4 - Find the audiostream
audioStreamIdx = -1;
for(uint i=0; i<fmtCtx->nb_streams; i++) {
    if(fmtCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
        audioStreamIdx = i;
        break;
    }
}

if(audioStreamIdx != -1) {
    // Step 5
    AVCodec *aCodec = avcodec_find_decoder(AV_CODEC_ID_MP3);
    AVCodecContext *audioDecCtx = avcodec_alloc_context3(aCodec);

    avcodec_open2(audioDecCtx, aCodec, NULL);

    // Step 6
    AVPacket pkt;
    AVFrame *frame = av_frame_alloc();

    av_init_packet(&pkt);

    pkt.data = NULL;
    pkt.size = 0;

    int got_packet = 0;

    while(av_read_frame(fmtCtx, &pkt) == 0) {
        int got_frame = 0;

        int ret = avcodec_decode_audio4(audioDecCtx, frame, &got_frame, &pkt);

        if(got_frame) {
            qDebug() << "got frame";
        }
    }

    av_free_packet(&pkt);
}

avformat_close_input(&fmtCtx);
现在它输出“get frame”,avcodec_decode_audio4()返回它解码的字节数


现在我必须将音频写入文件,最好是MP3文件。我发现我必须使用函数avcodec_encode_audio2()来完成。但是一些关于如何使用它的额外帮助是非常受欢迎的

是否确实要输出到MP3文件?这意味着从一种有损音频格式转换到另一种格式。也许你只是想要一个未压缩的PCM文件?嗨,迈克。是的,我真的想要一个MP3文件。原因是我正在从音乐视频中提取音频。用一些额外的代码制作了一个新主题。你能解决你的问题吗?
    // Step 5
    AVCodecContext *audioDecCtx = fmtCtx->streams[audioStreamIdx]->codec;
    AVCodec *aCodec = avcodec_find_decoder(audioDecCtx->codec_id);

    avcodec_open2(audioDecCtx, aCodec, NULL);