如何使用python中的moviepy在不同的时间戳向视频添加多个文本剪辑?

2024-09-27 07:27:09 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有textOnetextTwotextThree。每个变量的长度为10秒,必须每15秒插入一次。例如,textOne从00:00开始,到00:10结束。然后等待5秒钟,然后再插入textTwo10秒钟,依此类推。你将如何实现这一目标

请注意,在实际的应用程序中,您不仅仅需要设置10秒或每15秒等待一次的数字,每个数字可能都不同

使用Python 3.8.5、vs代码和迄今为止最新版本的moviepy


Tags: 代码版本应用程序目标数字vsmoviepy秒钟
1条回答
网友
1楼 · 发布于 2024-09-27 07:27:09

大概是这样的:

from moviepy.editor import *  

picture = VideoFileClip("img.jpg", audio=False).set_duration(50)

textOne = "First Line!"
textTwo = "Second Caption!!!!"
textThree = "Third one!!!"

texts = [textOne, textTwo, textThree]

step = 15 #each 15 sec: 0, 15, 30
duration = 10
t = 0
txt_clips = []
for text,i in zip(texts,range(0,3)):
  txt_clip = TextClip(text,fontsize = 40, color='white')
  txt_clip = txt_clip.set_start(t)
  txt_clip = txt_clip.set_pos('center').set_duration(duration)
  txt_clips.append(txt_clip)  
  t += step
  
audio = AudioFileClip(r"C:\Users\Public\Music\Sample Music\Kalimba.mp3").subclip(0,50)

video_with_new_audio = picture.set_audio(audio)

final_video = CompositeVideoClip([video_with_new_audio,txt_clips[0],txt_clips[1],txt_clips[2]])

final_video.write_videofile("TEXT.mp4")

为了获得更大的灵活性,您可以不使用范围(0,3)等,而是使用带有时间点和持续时间的列表,比如带有标题的列表;诸如此类:

starts = [0, 15, 30] # or whatever
durations = [10, 5, 7] 

for text,t,duration in zip(texts, starts, durations): 
    txt_clip = TextClip(text,fontsize = 40, color='white')
    txt_clip = txt_clip.set_start(t)
    txt_clip = txt_clip.set_pos('center').set_duration(duration)
    txt_clips.append(txt_clip)

相关问题 更多 >

    热门问题