gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:32:53 25 4
gpt4 key购买 nike

我有视频文件(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;
}

最佳答案

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

关于audio - FFMPEG - 无法使用 av_write_frame() 生成 aac 音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32622314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com