Python实现获取视频时长功能

这篇文章主要介绍了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获取视频时长内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是Python实现获取视频时长功能的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python