Automatically generate flash text video with Python

Today we will teach everyone

Automatically generate flash text video with Python

The most famous flash text video

It's Apple's 16 years of advertising

The text flashes with the music rhythm

The effect is simple and shocking

Although it seems to have been badly done in the past two years

I went out for a skewers two days ago and found that the store’s ads were all pop-ups

image-20200926113440597

But if you really want to do it, it’s actually a little troublesome

Whether you use PPT or Premier

You have to slowly align the drum rhythm

I’m afraid to make a video to loop this song hundreds of times

I don’t want to hear this song anymore

The effect is comparable to setting a song as an alarm clock in the morning

Nowadays!

Yuechuang is here to help you hard-working video practitioners

We use omnipotent Python

Automatically generate flash text video!

Even if the boss asks for a two-hour flash text video

Don't be afraid!

First of all, I will try it with a very famous song

The reform breeze blows all over the ground

The original work was created by Xiao Keer at station B

https://www.bilibili.com/video/av19390801

You can click to read the original text to watch

Then we look at the flash text video generated by the program automatically find the drum

In the video above

All drum beats are automatically found by the program

Video generation is also all done by the program

The only manual operation is

Split the text as needed

In fact, this step can also be omitted

For example, the following video

I use the word segmentation module

This news

https://news.163.com/19/0618/20/EHVSFA1J0001875P.html

Use flash text

Show up

The way this news is presented

Isn't it very interesting?

Of course, if every news article reads this way

It's probably exhausting...

If you want to get the Python code of this flash text directly

Can reply in the background: flash text

Next, we briefly explain how this code is implemented step by step

First of all, the modules we need to use are

books

moviepy

jieba

click

among them

librosa is used to analyze drum rhythm

moviepy is used to generate video

jieba is used to segment words

click is used to make command line tools

First import the modules we need

import librosa
from moviepy.editor import TextClip, CompositeVideoClip, AudioFileClip
import jieba
import click

Next, define our main function main()

There are 6 input parameters

width: the width of the generated video

height: the height of the generated video

text: The address of the text file containing the text

music: background music

word_split: Whether to split words automatically (splitting according to line breaks without automatic word splitting)

output: the file name of the generated video

At the same time we use click to help us

Make this python file into a command line tool

The usage of click is as follows

image-20200926113541276

See github for details

https://github.com/pallets/click

So our main() function becomes as follows

@click.command()
@click.option('--width', prompt='Width', default=360, help='The width of video clips')
@click.option('--height', prompt='Height', default=240, help='The height of video clips')
@click.option('--text', prompt='Text file', default='text.txt', help='The source text file')
@click.option('--music', prompt='Music file', default='改革春风吹满地.mp3', help='The music file')
@click.option('--word_split', prompt='Split words', default=False, help='Split words or not')
@click.option('--output', prompt='Output file', default='FlashText.mp4', help='The output file name')
def main(width, height, text, music, word_split, output):

The prompt parameter represents the input prompt that will pop up when running the program

default is the default value

That is, the value selected when the user directly enters

Next in the main() function

We do everything

First read in a text file with text

	with open(text, 'r', encoding='utf-8') as f:
		text_str = f.read()

Then we see whether to segment words according to the user's choice

	if word_split:
		seg_list = jieba.lcut(text_str)
		punct = set(''':!),.:;?]}¢'"、。〉》」』】〕〗〞︰︱︳﹐、﹒
		﹔﹕﹖﹗﹚﹜﹞!),.:;?|}︴︶︸︺︼︾﹀﹂﹄﹏、~¢
		々‖•·ˇˉ―--′’”([{£¥'"‵〈《「『【〔〖([{£¥〝︵︷︹︻
		︽︿﹁﹃﹙﹛﹝({“‘-—_…/\\''')
		word_list = list(filter(lambda x: x not in punct, seg_list))
	else:
		word_list = text_str.split('\n')

Here when word_split is True

We use jieba.lcut(text_str) to get the list after word segmentation

Similar to the picture below

Insert picture description here

Next we use two sentences to eliminate

Punctuation in the list after word segmentation

The most important one is to use the filter() function

Combine lambda to eliminate

It's a relatively simple way to remove symbols

And if word_split is False

Then we directly split the document with line breaks

After finishing dividing the text

Let's analyze the music drums

Here librosa can help a lot

librosa is a very powerful Python module

Various information of audio can be analyzed

Here we use its beat_track method

	y, sr = librosa.load(music)
	tempo, beats = librosa.beat.beat_track(y=y, sr=sr)
	beat_times = list(librosa.frames_to_time(beats, sr=sr))
	beat_times.append(beat_times[-1] + 1)

Eventually we will get a list of beat_times

It contains the time of each drum

At the same time you can notice the last line

beat_times.append(beat_times[-1] + 1)

Here I repeat the last digit of the list

And offset 1 second later

Mainly for us to deal with the video clip of the last drum beat later

After getting the drum time list

Let’s start making each text video clip

	clips = []
	for index, beat_time in enumerate(beat_times[:-1]):
		if index >= len(word_list):
			break
		print(f'{index + 1}/{len(beat_times)}——{word_list[index]}')
		text_clip = TextClip(
			word_list[index],
			fontsize=width // 8,
			color='white',
			size=(width, height),
			method='caption',
			font='msyhbd.ttc')\
			.set_start(beat_time)\
			.set_end(beat_times[index + 1])
		text_clip = text_clip.set_pos('center')
		clips.append(text_clip)

Here we use moviepy

moviepy is a python module that I personally like very much

A very powerful python video production module

I have the opportunity to talk more about the use of this module in the future

Here we use the moviepy text fragment

TextClip()

The first parameter is the specific text

Then you can set the font size, color, etc.

method='caption' means that the text is a caption

When TextClip is set to the title class

We can set size at the same time

When the text width exceeds size, it will wrap automatically

Then you can directly call the two methods in a chain

set_start()和set_end()

Used to set the start and end time of this video clip

Here we just set it as the time between a certain drum beat and the next drum beat

So we have completed the production of each text fragment video

Finally, to generate a complete video

	final_clip = CompositeVideoClip(clips)
	audio_clip = AudioFileClip(music)
	final_video = final_clip.set_audio(audio_clip)
	final_video.write_videofile(
		output,
		fps=30,
		codec='mpeg4',
		preset='ultrafast',
		audio_codec="libmp3lame",
		threads=4)

Use moviepy's CompositeVideoClip

To synthesize multiple video clips

Use AudioFileClip to make audio clips

Then synthesize

Finally, directly use the write_videofile() method to generate a complete video

Video and audio encoding can be set in this method

And frame rate FPS

Finally add

if __name__ == '__main__':
	main()

That's it!

So I want to make a simple flash text video in the future

Just run this python file

Enter information as prompted

Insert picture description here

You can wait for the program to do it for you

Is it super convenient?

This issue of Yuechuang Small Classroom is over here

Welcome to follow AI Yuechuang

I will continue to teach you some fun and interesting brain projects

Guess you like

Origin blog.csdn.net/qq_33254766/article/details/108814988