方法一: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()
CV2 Duration: 25.334 Time: 0.4679834842681885
Moviepy Duration: 25.33 Time: 3.32969069480896
FFMPEG Duration: 25.334000 Time: 0.6183815002441406
CV2 Duration: 1384.8 Time: 0.6656379699707031
Moviepy Duration: 1384.85 Time: 3.5491459369659424
FFMPEG Duration: 1384.853313 Time: 0.8809361457824707
CV2 Duration: 71.48 Time: 0.12198328971862793
Moviepy Duration: 71.48 Time: 2.4593451023101807
FFMPEG Duration: 71.480000 Time: 0.2852647304534912
参考
https://ffmpy3.readthedocs.io/en/latest/