python使用ffmpeg去掉视频片头和片尾
需要自己得到视频的片头和片尾时长;并且设置好视频文件的名称。 关于ffmpeg的配置及操作可看ffmpeg配置环境和测试,ffmpeg的基本使用,python操作ffmpeg
import os
import time
import subprocess
def renameFiles(dirPath):
list = []
files = os.listdir(dirPath)
for filename in files:
createTime = os.path.getctime(dirPath + filename)
list.append(str(int(createTime)) + '-' + filename)
list = sorted(list)
for i in range(len(list)):
oldName = list[i].split('-')[1]
suffix = list[i].split('.')[1]
newName = '0' + str(i + 1) + '.' + suffix
print(oldName,'-->',newName)
os.rename(dirPath + oldName, dirPath + newName)
def get_video_duration(video_path: str):
ext = os.path.splitext(video_path)[-1]
if ext != '.mp4' and ext != '.avi' and ext != '.flv':
raise Exception('format not support')
ffprobe_cmd = 'ffprobe -i {} -show_entries format=duration -v quiet -of csv="p=0"'
p = subprocess.Popen(
ffprobe_cmd.format(video_path),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
duration_info = float(str(out, 'utf-8').strip())
return int(duration_info)
def delete_av(path):
if os.path.exists(path):
os.remove(path)
print('yes')
else:
print("The file does not exist")
def video_cut(i,ss,t):
cmd = "ffmpeg -ss " + f'{ss}' + " -t " + f'{t}' + " -accurate_seek -i F:\\大明王朝1566\\0" + \
f'{i}' + ".mp4 -codec copy -avoid_negative_ts 1 F:\\大明王朝1566\\" + f'{i}' + ".mp4"
re = os.system(cmd)
time.sleep(1)
if re == 0:
print('成功')
else:
print('失败!!!!!!!!!!!!!!!!!!')
def mp4_ts(i):
cmd = "ffmpeg -i C:\\video\\" + f'{i}' + ".mp4 -vcodec copy -acodec copy -vbsf h264_mp4toannexb C:\\video\\" + f'{i}' + ".ts"
re = os.system(cmd)
time.sleep(1)
if re == 0:
print('转换成功')
else:
print('转换失败!!!!!!!!!!!!!!!!!!')
def mp4():
cmd = "ffmpeg -f concat -i F:\\大明王朝1566\\list.txt -c copy C:\\video\\output.mp4"
re = os.system(cmd)
time.sleep(1)
if re == 0:
print('合并成功')
else:
print('合并失败!!!!!!!!!!!!!!!!!!')
if __name__ == '__main__':
for index in range(1,47):
path = 'F:\\大明王朝1566\\0'+ f'{index}' +'.mp4'
t = get_video_duration(path) - 308
video_cut(index,90,t)
print('over')
time.sleep(2)
|