У меня есть видеофайл (mp4). Я хочу отключить аудио-поток (формат AAC) из этого файла и сохранить на ПК. С помощью нижеприведенного кода я использую av_write_frame() для записи пакета. Тогда сгенерированный файл не может воспроизводиться. Но, если я использую fwrite() для записи пакета в файл (например, это FFMPEG- Duration of audio file is inaccurate). Затем может воспроизводиться сгенерированный файл.FFMPEG - невозможно создать звуковой файл aac с помощью av_write_frame()
Итак, как использовать 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;
}
Пожалуйста, примите ваш собственный ответ –