采用ffmpeg 4.0版本以上,创建一个mp4文件的程序
时间: 2024-03-06 17:51:23 浏览: 16
下面是使用ffmpeg 4.0以上版本创建一个mp4文件的程序示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
int main(int argc, char *argv[]) {
AVFormatContext *format_ctx = NULL;
AVOutputFormat *output_fmt = NULL;
AVCodec *codec = NULL;
AVCodecContext *codec_ctx = NULL;
AVStream *stream = NULL;
AVPacket pkt;
int ret, i;
// 初始化ffmpeg库
av_register_all();
// 创建输出格式上下文
ret = avformat_alloc_output_context2(&format_ctx, NULL, NULL, "output.mp4");
if (ret < 0) {
fprintf(stderr, "Could not allocate output format context: %s\n", av_err2str(ret));
return 1;
}
output_fmt = format_ctx->oformat;
// 添加音频流
codec = avcodec_find_encoder(output_fmt->audio_codec);
if (!codec) {
fprintf(stderr, "Could not find audio encoder\n");
return 1;
}
stream = avformat_new_stream(format_ctx, codec);
if (!stream) {
fprintf(stderr, "Could not allocate audio stream\n");
return 1;
}
codec_ctx = avcodec_alloc_context3(codec);
if (!codec_ctx) {
fprintf(stderr, "Could not allocate audio codec context\n");
return 1;
}
codec_ctx->sample_fmt = AV_SAMPLE_FMT_S16;
codec_ctx->sample_rate = 44100;
codec_ctx->channels = 2;
codec_ctx->channel_layout = AV_CH_LAYOUT_STEREO;
if (format_ctx->oformat->flags & AVFMT_GLOBALHEADER)
codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
ret = avcodec_open2(codec_ctx, codec, NULL);
if (ret < 0) {
fprintf(stderr, "Could not open audio codec: %s\n", av_err2str(ret));
return 1;
}
ret = avcodec_parameters_from_context(stream->codecpar, codec_ctx);
if (ret < 0) {
fprintf(stderr, "Could not set audio codec parameters: %s\n", av_err2str(ret));
return 1;
}
// 打开输出文件
ret = avio_open(&format_ctx->pb, "output.mp4", AVIO_FLAG_WRITE);
if (ret < 0) {
fprintf(stderr, "Could not open output file: %s\n", av_err2str(ret));
return 1;
}
// 写文件头
ret = avformat_write_header(format_ctx, NULL);
if (ret < 0) {
fprintf(stderr, "Error writing header: %s\n", av_err2str(ret));
return 1;
}
// 写音频数据
for (i = 0; i < 100; i++) {
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
ret = avcodec_send_frame(codec_ctx, frame);
if (ret < 0) {
fprintf(stderr, "Error sending frame: %s\n", av_err2str(ret));
return 1;
}
while (ret >= 0) {
ret = avcodec_receive_packet(codec_ctx, &pkt);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
break;
else if (ret < 0) {
fprintf(stderr, "Error receiving packet: %s\n", av_err2str(ret));
return 1;
}
pkt.stream_index = stream->index;
ret = av_interleaved_write_frame(format_ctx, &pkt);
if (ret < 0) {
fprintf(stderr, "Error writing audio frame: %s\n", av_err2str(ret));
return 1;
}
}
}
// 写文件尾
av_write_trailer(format_ctx);
// 释放资源
avformat_free_context(format_ctx);
avcodec_free_context(&codec_ctx);
return 0;
}
```
此程序创建了一个输出格式上下文,添加了一个音频流,并打开输出文件 `output.mp4`。然后,循环写入100帧音频数据。最后,程序写入文件尾,释放资源并返回。