使用moviepy.editor剪辑视频,批量截取视频片段

python分享 (351) 2023-04-17 11:59:40
#!/usr/bin/env python

import os
from moviepy.editor import *

def listFile(dir):
    dirs = os.listdir(dir)
    for file in dirs:
        f_p = os.path.join(dir,file)
        print(f_p)

def t2s(t):
    times = t.strip().split(":")
    if len(times) == 3:
        h,m,s = times
    elif len(times) == 2:
        h = 0
        m,s = times
    else:
        return int(times[0])
    return int(h) * 3600 + int(m) * 60 + int(s)



def sublipFromtimes(f_p):
    with open("yhtimes.txt") as f:
        times = f.readlines()
    times = [x.strip() for x in times] 
    for time in times:
        starttime = int(time.split("-")[0])
        endtime = int(time.split("-")[1])
        subclip(f_p, str(times.index(time)+1)+".mp4", starttime, endtime)

def sublipFromHms(f_p):
    with open("hms.txt") as f:
        times = f.readlines()
    times = [x.strip() for x in times] 
    for time in times:
        starttime = t2s(time.split("-")[0])
        endtime = t2s(time.split("-")[1])
        subclip(f_p, str(times.index(time)+1)+".mp4", starttime, endtime)


def subclip(f_p,o_p,start,end=0):

    videoclip = VideoFileClip(f_p)
    if end==0:
        end = videoclip.duration
    videoclip_new = videoclip.subclip(start,end)
    videoclip_new.write_videofile(o_p)

def concatclip(o_p,clips):
    # 传入数组clips
    videoclip_new = concatenate_videoclips(clips)
    videoclip_new.write_videofile(o_p)

def addLogo(f_p,o_p,logo):
    video = VideoFileClip(f_p)
    #准备log图片
    logo = (ImageClip(logo)
        .set_duration(video.duration) # 水印持续时间
        .resize((500,300)) # 水印的高度,会等比缩放
        .margin(right=0, top=0, opacity=1) # 水印边距和透明度
        .set_pos(("left","top"))) # 水印的位置
    result = CompositeVideoClip(
[video, logo]
) #在视频上覆盖
    result.write_videofile(o_p,fps=25)#fps:视频文件中每秒的帧数

def updateDir(dir):
    #修改文件夹名字
   for d_n in os.listdir(dir):
       d_n =  os.path.join(dir,d_n)
       os.rename(d_n,d_n.replace('王者',''))

if __name__ == '__main__':
    print(t2s('00:00:11:55'))

 

THE END

发表回复