python 获取视频的时长

以下是几种获取视频时长的实现方法:

方法一:使用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
相关推荐
lpfasd1232 小时前
火山引擎 TOS 视频 `Content-Disposition: attachment` 排查实录
音视频·火山引擎
idingzhi2 小时前
A股量化策略日报(2026年07月12日)
python
二宝哥3 小时前
07.Python运算符详解与编码基础
python
byte轻骑兵3 小时前
【LE Audio】CSIS精讲[1]: 从核心定义到协议基础,读懂多设备协同的底层逻辑
人工智能·音视频·人机交互·蓝牙耳机·le audio·低功耗蓝牙音频
巴啦啦小魔仙变身3 小时前
SIGINT = Signal Interrupte
linux·服务器·python
Maiko Star3 小时前
Python项目实战——网络机器人(爬虫)
爬虫·python·机器人
xlrqx3 小时前
2026年沧州家电清洗培训成本核算方法及成本控制要点
大数据·python
许彰午3 小时前
85_Python Flask开发RESTful API
python·flask·restful
梦想不只是梦与想3 小时前
OmegaConf 配置管理库的使用
python·omegaconf·结构化配置
中微极客4 小时前
从提示词到产品级视频:生成式AI的工程化实践与工具栈选型(LTX Studio实战)
人工智能·chatgpt·音视频