FFMPEG - 使用av_write_frame()无法生成aac音频文件

时间:2015-09-17 03:52:51

标签: audio video ffmpeg

我有视频文件(mp4)。我想从该文件中分离音频流(AAC格式)并保存在PC中。 使用下面的代码,我使用av_write_frame()来写入数据包。然后,生成的文件无法播放。 但是,如果我使用fwrite()将数据包写入文件(如此FFMPEG- Duration of audio file is inaccurate)。然后,生成的文件可以播放。

那么,如何以正确的方式使用av_write_frame()以便生成可以播放?

    int save_detached_audio(AVFormatContext **input_format_context,
                                AVStream **input_audio_stream,
                                AVCodecContext **input_codec_context,
                                const char *filename) {
int ret;
AVCodec *codec = avcodec_find_decoder((*input_codec_context)->codec_id);
if (!codec) {
    av_log(NULL, AV_LOG_FATAL, "Failed to find codec of detached audio.\n");
    return -1;
}

AVFormatContext* output_format_context = NULL;
AVStream* output_stream = NULL;
ret = avformat_alloc_output_context2(&output_format_context, NULL, NULL, filename);
if (!output_format_context) {
    av_log(NULL, AV_LOG_FATAL, "Could not allocate output format context.\n");
    return -1;
}


// open output file to write to it.
ret = avio_open2(&output_format_context->pb, filename, AVIO_FLAG_WRITE, NULL, NULL);
if (ret < 0) {
    av_log(NULL, AV_LOG_FATAL, "Could not open output file to write to it.\n");
    return -1;
}

AVOutputFormat* fmt = NULL;
fmt = av_guess_format(NULL, filename, NULL);
if (!fmt) {
    av_log(NULL, AV_LOG_FATAL, "Could not find file format of detached audio.\n");
    return -1;
}

output_format_context->oformat = fmt;

// Create a new audio stream in the output file container. 
output_stream = avformat_new_stream(output_format_context, codec);
if (!output_stream) {
    av_log(NULL, AV_LOG_FATAL, "Could not create a new stream in the output file container.\n");
    return -1;
}

output_stream->codec->bit_rate = (*input_codec_context)->bit_rate;
output_stream->codec->sample_rate = (*input_codec_context)->sample_rate;
output_stream->codec->channels = (*input_codec_context)->channels;


 ret = avformat_write_header(output_format_context, NULL);
 if (ret < 0) {
     av_log(NULL, AV_LOG_FATAL, "Could not write header to output.\n");
     return -1;
 }

AVPacket reading_packet;
av_init_packet(&reading_packet);
while (av_read_frame(*input_format_context, &reading_packet) == 0) {
    if (reading_packet.stream_index == (*input_audio_stream)->index) {
        reading_packet.stream_index = 0;
        ret = av_write_frame(output_format_context, &reading_packet);
    }
    av_free_packet(&reading_packet);   
}
 ret = av_write_trailer(output_format_context);
 if (ret < 0) {
     av_log(NULL, AV_LOG_FATAL, "Could not write trailer to output.\n");
     return -1;
 }

1 个答案:

答案 0 :(得分:1)

问题解决了。 因为aac音频流被写入文件。因此,我们需要为output_codec_context分配extradata和extradata_size的值。这两个值可以从input_codec_context

中获取