ffmpeg create blank screen with text video

2020-05-13 20:55发布

问题:

I would like to create a video consisting of some text. The video will only be 0.5 seconds long. The background should just be some colour, I am able to create such video from a photo, but cant find anywhere how this could be done without a photo, just using text to create such video.

Can you help me ? Thanks in advance

回答1:

Add text to solid color background

Use the color video source filter and the drawtext video filter.

ffmpeg -f lavfi -i color=c=blue:s=320x240:d=0.5 -vf \
"drawtext=fontfile=/path/to/font.ttf:fontsize=30: \
 fontcolor=white:x=(w-text_w)/2:y=(h-text_h)/2:text='Stack Overflow'" \
output.mp4
  • The d=0.5 will make a 0.5 second duration output.
  • See the list of supported color names and how to use a hex code to set color.

With a transparent box behind text

Another example with a white box behind the text at 25% opacity with 5 pixel padding:

ffmpeg -f lavfi -i color=c=red:s=320x240:d=0.5 -vf \
"drawtext=fontfile=/path/to/font.ttf:fontsize=30: \
 box=1:boxborderw=5:boxcolor=white@0.25: \
 fontcolor=white:x=(w-text_w)/2:y=(h-text_h)/2:text='Stack Overflow'" \
output.mp4

Multiple lines


It's easier to center the two lines with multiple drawtext instances (left image). Right image is from the external file and line break examples.

You can chain together two drawtext filters, or reference an external text file with the textfile option, or add the line break in the command.

Multiple drawtext instances

ffmpeg -f lavfi -i color=c=green:s=320x240:d=0.5 -vf \
"drawtext=fontfile=/path/to/font.ttf:fontsize=30:fontcolor=white:x=(w-text_w)/2:y=(h-text_h-text_h)/2:text='Stack', \
 drawtext=fontfile=/path/to/font.ttf:fontsize=30:fontcolor=white:x=(w-text_w)/2:y=(h+text_h)/2:text='Overflow'" \
output.mp4

External text file

The contents of the text file, text.txt, looks like this:

Stack
Overflow

The ffmpeg command:

ffmpeg -f lavfi -i color=c=green:s=320x240:d=0.5 -vf \
"drawtext=fontfile=/path/to/font.ttf:fontsize=30: \
 fontcolor=white:x=(w-text_w)/2:y=(h-text_h)/2:textfile=text.txt" \
output.mp4

Line break in command

ffmpeg -f lavfi -i color=c=green:s=320x240:d=0.5 -vf \
"drawtext=fontfile=/path/to/font.ttf:fontsize=30: \
fontcolor=white:x=(w-text_w)/2:y=(h-text_h)/2:text='Stack
Overflow'" \
output.mp4

Output image instead of video

If you want an image output instead replace output.mp4 with -frames:v 1 output.png.

Alternative method

Using the subtitles filter is another method to do this.