我试图将单张图片编码成一个.avi视频。我的目标是让每张图片显示一定的秒数来创建一个幻灯片。我试着用10张图片和15秒的延迟来制作脚本,但输出文件连半秒都没有(但显示了每张图片)。我使用AVCodeContext的time_base选项来设置帧率。
ctx->time_base = (AVRational) {1, 5};
当我使用命令 ffmpeg -framerate 1/3 -i img%03d.png -codec png output.avi
一切工作正常,我得到了我想要的文件。我使用png编解码器,因为这是我尝试过的唯一一个可以用Windows Media Player播放的编解码器。
我在这里错过了什么吗?是否有其他选项对帧率有影响?
这是我目前的代码。
注: 我使用了一些自制的数据结构和其他类的方法。它们是用Caps Lock写的。它们的基本功能和名字一样,但对我的项目来说是必要的。输入数组包含我想编码的图片。
include <libavutil/opt.h>
include <libavutil/imgutils.h>
include <libavutil/error.h>
void PixmapsToAVI (ARRAY* arr, String outfile, double secs)
{
if (arr!=nil && outfile!="" && secs!=0) {
AVCodec* codec = avcodec_find_encoder(AV_CODEC_ID_PNG);
if (codec) {
int width = -1;
int height = -1;
int ret = 0;
AVCodecContext* ctx = NULL;
ctx = avcodec_alloc_context3(codec);
AVFrame* frame = av_frame_alloc();
AVPacket* pkt = av_packet_alloc();
FILE* file = fopen(outfile, "wb");
ARRAYELEMENT* e;
int count = 0;
forall (e, *arr) {
BITMAP bitmap (e->value, false);
if (width < 0) {
width = bitmap.Width();
height = bitmap.Height();
ctx->width = width;
ctx->height = height;
ctx->time_base = (AVRational){1, 5};
ctx->framerate = (AVRational){5, 1};
ctx->pix_fmt = AV_PIX_FMT_RGB24;
ret = avcodec_open2(ctx, codec, NULL);
frame->width = width;
frame->height = height;
frame->format = ctx->pix_fmt;
av_opt_set(ctx->priv_data, "preset", "slow", 1);
}
ret = av_frame_get_buffer(frame, 1);
frame->linesize[0] = width*3;
bitmap.Convert32();
byte* pixels = bitmap.PixelsRGB();
//The two methodes above convert the Pixmap into the RGB structure we need
//They are not needed to get an output file but are needed to get one that makes sense
fflush(stdout);
int writeable = av_frame_make_writable(frame);
if (writeable>=0) {
for(int i=0; i<(height*width*3); i++){
frame->data[0][i] = pixels[i];
}
}
ret = avcodec_send_frame(ctx, frame);
for(int i=0; i<secs; i++){
fflush(stdout);
avcodec_send_frame(ctx, frame);
}
while (ret >= 0) {
ret = avcodec_receive_packet(ctx, pkt);
}
count++;
avcodec_receive_packet(ctx, pkt);
fwrite(pkt->data, 1, pkt->size, file);
fflush(stdout);
av_packet_unref(pkt);
}
fclose(file);
avcodec_free_context(&ctx);
av_frame_free(&frame);
av_packet_free(&pkt);
}
}
}
png编解码器,因为它是唯一一个我试过的可以用Windows Media Player播放的编解码器。
试着安装媒体播放器的K-lite编解码器包,它可以帮助显示其他格式。https:/codecguide.comdownload_k-lite_codec_pack_basic.htm。
我试了一下我的脚本,有10张图片,延迟15秒,但输出文件连半秒都没有(但显示每张图片)。
ctx->time_base = (AVRational) {1, 5};
/* frames per second */
c->time_base = (AVRational){1, 25};
c->framerate = (AVRational){25, 1};
请看下面的参考资料可能对你有帮助。https:/libav.orgdocumentationdoxygenmasterencode_video_8c-example.html#a25。