2

I am trying to write a C++ program that allows me to extract the audio from a video file to an mp3 file. I searched the internet and stackoverflow, but couldn't get it to work.

The library I chose is ffmpeg and I have to do it in C/C++. This is what I have so far.

// 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);

But the error I get when executing avcodec_decode_audio4() is "[mp3 @ 825fc30] Header missing".

Thanks in advance!

[EDIT] I found out that the audio of the video was not MP3 but AAC. So I changed Step 5 to the following lines of code

    // Step 5
    AVCodecContext *audioDecCtx = fmtCtx->streams[audioStreamIdx]->codec;
    AVCodec *aCodec = avcodec_find_decoder(audioDecCtx->codec_id);

    avcodec_open2(audioDecCtx, aCodec, NULL);

Now it outputs "got frame" and the avcodec_decode_audio4() returns the number of bytes it decoded.

Now I have to write the audio to a file, preferably to an MP3 file. I found out that I have to do it with the function avcodec_encode_audio2(). But some extra help on how to use it is more then welcome!

0 Answers0