python3获取视频文件播放时长的三种方法
更新时间:2024年04月19日 11:22:12 作者:小龙在山东
这篇文章主要介绍了python3获取视频文件播放时长的三种方法,VideoFileClip,CV2以及FFmpeg这三种方法,文章通过代码示例给大家讲解的非常详细,需要的朋友可以参考下
方法一:VideoFileClip
from moviepy.editor import VideoFileClip def get_duration_from_moviepy(url): clip = VideoFileClip(url) return clip.duration
方法二:CV2
最快。
下载安装:https://github.com/opencv/opencv/releases
pip install opencv-python
import cv2 def get_duration_from_cv2(filename): cap = cv2.VideoCapture(filename) if cap.isOpened(): rate = cap.get(5) frame_num =cap.get(7) duration = frame_num/rate return duration return -1
方法三:FFmpeg
pip install ffmpy3
import ffmpy3 def get_duration_from_ffmpeg(url): tup_resp = ffmpy3.FFprobe( inputs={url: None}, global_options=[ '-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams' ] ).run(stdout=subprocess.PIPE) meta = json.loads(tup_resp[0].decode('utf-8')) return meta['format']['duration']
速度比较
import json import subprocess import time import cv2 import ffmpy3 from moviepy.editor import VideoFileClip ls = [ "https://test/1.mp4", "http://test/2.mp4", "https://test/3.mp4" ] def get_duration_from_cv2(filename): cap = cv2.VideoCapture(filename) if cap.isOpened(): rate = cap.get(5) frame_num =cap.get(7) duration = frame_num/rate return duration return -1 def get_duration_from_moviepy(url): clip = VideoFileClip(url) return clip.duration def get_duration_from_ffmpeg(url): tup_resp = ffmpy3.FFprobe( inputs={url: None}, global_options=[ '-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams' ] ).run(stdout=subprocess.PIPE) meta = json.loads(tup_resp[0].decode('utf-8')) return meta['format']['duration'] for u in ls: t1 = time.time() p = get_duration_from_cv2(u) t2 = time.time() print('CV2 Duration: ', p, ' Time: ', t2 - t1) t1 = time.time() p = get_duration_from_moviepy(u) t2 = time.time() print('Moviepy Duration: ', p, ' Time: ', t2 - t1) t1 = time.time() p = get_duration_from_ffmpeg(u) t2 = time.time() print('FFMPEG Duration: ', p, ' Time: ', t2 - t1) print()
参考
https://ffmpy3.readthedocs.io/en/latest/
到此这篇关于python3获取视频文件播放时长的三种方法的文章就介绍到这了,更多相关python3获取视频播放时长内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
最新评论