使用ffmpeg判断视频格式并转码

闲来无事,想写个脚本处理下电脑上的电影,从网上下载的电影有各种编码格式,通过 ftp 共享给手机看不能硬解,遂写了个脚本将所有编码格式不是 H.264 的电影打印出来,后续将其转成 H.264 编码格式。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# -*- coding: utf-8 -*-
import os
import json
import subprocess

files = []
# 遍历出所有的文件,这里没有做文件类型判断,因为视频的封装格式有好多种,就不一一列举了
for path, dir_list, file_list in os.walk(r'd:\xxx'):
for a in file_list:
if '~' in a or '$' in a:
continue
files.append(os.path.join(path, a))
for a in files:
# 通过ffprobe来输出视频文件的信息
result = subprocess.Popen(f'ffprobe.exe -hide_banner -print_format json -show_streams "{a}"',
shell=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
)
# 等待程序结束然后输出json格式的信息
out, err = result.communicate()
result = json.loads(out.decode())['streams']
# 判断是否是指定的编码格式,如果不是则输出
if '"codec_long_name": "H.264' not in out.decode() and '"codec_long_name": "AAC' not in out.decode():
print(a, f'{round(os.path.getsize(a) / (1024 * 1024), 2)}M')
for b in result:
print(f"{b['codec_type']}:{b['codec_long_name']}")

输出示例如下:

1
2
3
4
5
6
7
8
9
10
d:\xxx\111 801.36M
video:Windows Media Video 9
audio:Windows Media Audio 2
d:\xxx\222 978.25M
video:Windows Media Video 9
audio:Windows Media Audio 2
d:\xxx\333 446.29M
video:Windows Media Video 9
audio:Windows Media Audio 2
d:\xxx\444 905.61M

通过 ffmpeg 转换成对应的 H.264 格式。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- coding: utf-8 -*-
import subprocess
import time

result = subprocess.Popen(r'ffmpeg.exe -y -i d:\xxx d:\xxx.mp4',
shell=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf8') #
while result.poll() is None:
print(result.stdout.readline().strip())
time.sleep(0.1)

通过 subprocess 调用 ffmpeg.exe 来进行转码,调用 poll 函数来判断是否转码成功,通过循环调用 stdout 属性可以做到实时输出 ffmpeg 的输出,动手能力强的小伙伴可以尝试实现自定义输出进度和剩余时间。

这里需要注意的是,循环调用 stdout 属性的方式来获取输出是没有问题的,但是要加一个小小的延时,因为如果 ffmpeg 还没有打印输出的话调用 stdout 属性的话会输出一个空行。

其实完全可以实现通过过滤后缀名来过滤出所有的视频文件,然后将上边这段代码放入到上一段代码的循环里,实现自动转码所有不符合编码格式的视频,实现无人值守。嘿嘿,我需要转换的视频比较少,所有就不写了。

参考链接:

https://blog.csdn.net/cnweike/article/details/73620250

本文章首发于个人博客 LLLibra146’s blog
本文作者:LLLibra146
版权声明:本博客所有文章除特别声明外,均采用 © BY-NC-ND 许可协议。非商用转载请注明出处!严禁商业转载!
本文链接https://blog.d77.xyz/archives/ee721c2.html