c语言中怎么调用ffmpeg合成视频

2024-04-16

在C语言中调用ffmpeg合成视频,可以使用ffmpeg提供的API来实现。下面是一个简单的示例代码,演示了如何使用ffmpeg API来合成视频:

#include <stdio.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/error.h>

int main() {
    av_register_all();

    AVFormatContext *formatContext;
    avformat_alloc_output_context2(&formatContext, NULL, NULL, "output.mp4");
    if (!formatContext) {
        fprintf(stderr, "Error allocating format context\n");
        return AVERROR_UNKNOWN;
    }

    AVStream *videoStream = avformat_new_stream(formatContext, NULL);
    if (!videoStream) {
        fprintf(stderr, "Error creating video stream\n");
        return AVERROR_UNKNOWN;
    }

    AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_H264);
    if (!codec) {
        fprintf(stderr, "Codec not found\n");
        return AVERROR_UNKNOWN;
    }

    videoStream->codecpar->codec_id = AV_CODEC_ID_H264;
    videoStream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
    videoStream->codecpar->width = 640;
    videoStream->codecpar->height = 480;
    videoStream->codecpar->format = AV_PIX_FMT_YUV420P;

    AVDictionary *options = NULL;
    av_dict_set(&options, "preset", "ultrafast", 0);

    avformat_write_header(formatContext, &options);

    // Write frames to video stream

    av_write_trailer(formatContext);
    avio_closep(&formatContext->pb);
    avformat_free_context(formatContext);

    return 0;
}

在上面的示例中,我们首先注册了ffmpeg库,然后创建了一个输出格式的上下文。接着创建了一个视频流,并设置了视频编码器为H.264。然后设置了视频流的参数,比如宽高和像素格式。之后通过avformat_write_header函数写入文件头,然后写入视频帧数据到视频流中。最后调用av_write_trailer函数写入文件尾,关闭文件并释放资源。

需要注意的是,上面的示例代码只是一个简单的示例,实际使用时需要根据具体需求进行修改和完善。