以下是几种获取视频时长的实现方法:
方法一:使用moviepy库
python
from moviepy.editor import VideoFileClip
def get_video_duration(file_path):
video = VideoFileClip(file_path)
duration = video.duration
video.close()
return duration
方法二:使用cv2库
python
import cv2
def get_video_duration(file_path):
video = cv2.VideoCapture(file_path)
frame_count = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
fps = video.get(cv2.CAP_PROP_FPS)
duration = frame_count / fps
video.release()
return duration
方法三:使用ffprobe命令行工具
python
import subprocess
def get_video_duration(file_path):
result = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', file_path], capture_output=True, text=True)
duration = float(result.stdout)
return duration