Python实现获取视频时长功能

发布时间:2022-04-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Python实现获取视频时长功能脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

前言

本文提供获取视频时长的python代码,精确到毫秒,一如既往的实用主义。

环境依赖

 ffmPEg环境安装,可以参考:windows ffmpeg安装部署

本文主要使用到的不是ffmpeg,而是ffPRobe也在上面这篇文章中的zip包中。

代码

不废话,上代码。

#!/user/bin/env python
# coding=utf-8
"""
@project : csdn
@author  : 剑客阿良_ALiang
@file   : get_video_duration.py
@ide    : Pycharm
@time   : 2021-12-23 13:52:33
"""
 
import os
import subprocess
 
 
def get_video_duration(video_path: str):
    ext = os.path.splIText(video_path)[-1]
    if ext != '.mp4' and ext != '.avi' and ext != '.flv':
        raise Exception('format not support')
    ffprobe_cmd = 'ffprobe -i {} -show_entries format=duration -v quiet -of csv="p=0"'
    p = subprocess.Popen(
        ffprobe_cmd.format(video_path),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True)
    out, err = p.COMmunicate()
    print("subprocess 执行结果:out:{} err:{}".format(out, err))
    duration_info = float(str(out, 'utf-8').strip())
    return int(duration_info * 1000)
 
 
if __name__ == '__main__':
    print('视频的duration为:{}ms'.format(get_video_duration('D:/tmp/100.mp4')))

代码说明:

1、对视频的后缀格式做了简单的校验,如果需要调整可以自己调整一下。

2、对输出的结果做了处理,输出int类型的数据,方便使用。

验证一下

准备的视频如下:

验证一下

补充

Python实现获取视频fps

#!/user/bin/env python
# coding=utf-8
"""
@project : csdn
@author  : 剑客阿良_ALiang
@file   : get_video_fps.py
@ide    : PyCharm
@time   : 2021-12-23 11:21:07
"""
import os
import subprocess
 
 
def get_video_fps(video_path: str):
    ext = os.path.splitext(video_path)[-1]
    if ext != '.mp4' and ext != '.avi' and ext != '.flv':
        raise Exception('format not support')
    ffprobe_cmd = 'ffprobe -v error -select_streams v -of default=noprint_wrappers=1:nokey=1 -show_entries stream=r_frame_rate {}'
    p = subprocess.Popen(
        ffprobe_cmd.format(video_path),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True)
    out, err = p.communicate()
    print("subprocess 执行结果:out:{} err:{}".format(out, err))
    fps_info = str(out, 'utf-8').strip()
    if fps_info:
        if fps_info.find("/") > 0:
            video_fps_str = fps_info.split('/', 1)
            fps_result = int(int(video_fps_str[0]) / int(video_fps_str[1]))
        else:
            fps_result = int(fps_info)
    else:
        raise Exception('get fps error')
    return fps_result
 
 
if __name__ == '__main__':
    print('视频的fps为:{}'.format(get_video_fps('D:/tmp/100.mp4')))

代码说明:

1、首先对视频格式做了简单的判断,这部分可以按照需求自行调整。

2、通过subprocess进行命令调用,获取命令返回的结果。注意范围的结果为字节串,需要调整格式处理。

验证一下

下面是准备的素材视频,fps为25,看一下执行的结果。

执行结果

到此这篇关于Python实现获取视频时长功能的文章就介绍到这了,更多相关Python获取视频时长内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的Python实现获取视频时长功能全部内容,希望文章能够帮你解决Python实现获取视频时长功能所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: