更新
刚发现ffmpeg居然也有人开发了python的包,所以也可以直接使用ffmpeg-python [https://github.com/kkroening/ffmpeg-python],更方便一些。
pip install ffmpeg-python
------------
有时候我们获取文件夹里面的所有视频的长度,或者挑选出大于某个长度的视频,这时候可以使用ffmepg,也可以借助moviepy这个python库来解决这个问题。
安装 moviepy很简单,只需要:
pip install moviepy
以下代码是获取指定文件夹下,所有大于指定时间的视频路径,并保存到一个txt文件当中。
# encoding: utf-8
"""
ray
"""
import os
import datetime
import sys
import argparse
from moviepy.editor import VideoFileClip
#import ffmpeg # https://github.com/kkroening/ffmpeg-python
def get_video_list(dataset_path, save_path, type, vtime):
filelist = []
for a, b, c in os.walk(dataset_path):
for name in c:
fname = os.path.join(a, name)
if fname.endswith(type):
filelist.append(fname)
video_filelist = []
total_ftime = 0.0
for item in filelist:
clip = VideoFileClip(item)
ftime = clip.duration
#ftime = float(ffmpeg.probe(item)['format']['duration']) #如果用这个就注释掉上面两行
if ftime >= vtime:
video_filelist.append(item)
total_ftime += ftime
# print(item)
# print(ftime)
with open(save_path, 'w') as f:
for fn in video_filelist:
f.write(fn + "\n")
print("Total file number %d: " % len(video_filelist))
print("Total video time %d seconds: " % total_ftime, str(datetime.timedelta(seconds=total_ftime)))
return video_filelist
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Compute Time of a Series of Videos')
parser.add_argument("--path", metavar="PATH", default="/Users/xxx/Downloads/video",
help="the root path of the videos(default: .)")
parser.add_argument("--save_path", metavar="PATH", default="./video_list.txt",
help="the root path of the videos(default: .)")
parser.add_argument("--type", metavar="TYPE", default=".mp4",
help="the type of the videos(default: .mp4)")
parser.add_argument('--vtime', type=float, default=5.0, help="select the videos which longer than vtime sceonds")
args = parser.parse_args()
video_filelist = get_video_list(args.path,args.save_path,args.type,args.vtime)