简介:在视频相关测试场景下,例如:有时需要知道全部视频的汇总时长,显然一个个打开并且手工计算耗时耗力,我们可以通过编写脚本进行快速汇总。
获取视频时长的方式:
1、通过subprocess进行获取。
2、通过moviepy库中VideoFileClip获取。
3、通过cv2库获取。
安装:
1、subprocess:无需安装,Python内置。
2、moviepy:pip install moviepy。
3、cv2:pip install opencv-python
准备工序:
1、当前项目新增videos目录。
2、you-get 下载几个视频。python:超实用下载工具you-get
如:下载了两个短视频
获取视频时长的3种方式对比:
import cv2 import time import subprocess from moviepy.editor import VideoFileClip def video_duration_1(filename): start = time.time() result = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) end = time.time() spend = end - start print("获取视频时长方法1耗时:", spend) return float(result.stdout) def video_duration_2(filename): start = time.time() clip = VideoFileClip(filename) end = time.time() spend = end - start print("获取视频时长方法2耗时:", spend) return float(clip.duration) def video_duration_3(filename): start = time.time() cap = cv2.VideoCapture(filename) if cap.isOpened(): rate = cap.get(5) frame_num = cap.get(7) duration = frame_num / rate end = time.time() spend = end - start print("获取视频时长方法3耗时:", spend) return duration return -1 if __name__ == '__main__': file = r".videosmda-mkbhvebqej3cw9yh.mp4" video_time_1 = video_duration_1(file) print(video_time_1) print("*" * 100) video_time_2 = video_duration_2(file) print(video_time_2) print("*" * 100) video_time_3 = video_duration_3(file) print(video_time_3)
执行源码:
结论:
1、三种方式均可以正常获取视频时长,并且准确。
2、推荐使用cv2获取视频时长,耗时最短。
实践案例:获取文件夹内全部视频总时长
import cv2 import os def video_duration(dir_name): sum_duration = 0 for root, dirs, files in os.walk(dir_name, topdown=False): for filename in files: cap = cv2.VideoCapture(dir_name + "\" + filename) if cap.isOpened(): rate = cap.get(5) frame_num = cap.get(7) duration = frame_num / rate sum_duration += duration return sum_duration if __name__ == '__main__': file = r".videos" total_video_time = video_duration(file) print(f"{file} 目录下全部视频总时长为:{total_video_time}秒")
微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)