Skip to content

Commit 9e943e5

Browse files
committed
split_video
1 parent e33a98f commit 9e943e5

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

taiyangxue/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Python 代码实例
22

3+
- [split-video](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/split-video) : 神器 ffmpeg —— 实现短视频批量化操作
34
- [pypandoc](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/pypandoc) : 神器 Pypandoc —— 实现电子书自由
45
- [python-thread](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/python-thread) : 这么一搞,再也不怕线程打架了
56
- [python-op2](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/python-op2) : 只需一招,Python 将系统秒变在线版!

taiyangxue/split-video/split_video.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import math
2+
import os
3+
4+
# 获取视频时长
5+
import subprocess as sp
6+
def get_video_duration(filename):
7+
8+
cmd = "ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 -i %s" % filename
9+
print(cmd)
10+
p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
11+
p.wait()
12+
# p.stdout
13+
strout, strerr = p.communicate() # 去掉最后的回车
14+
print(strout, strerr)
15+
ret = strout.decode("utf-8").strip() # 去掉最后的回车
16+
print(ret)
17+
return ret
18+
19+
20+
# 将视频拆分成一分钟的小段
21+
def cut_video(filename, outfile, start, length=90):
22+
cmd = "ffmpeg -i %s -ss %d -t %d -c copy %s" % (filename, start, length, outfile)
23+
p = sp.Popen(cmd, shell=True)
24+
p.wait()
25+
return
26+
27+
# 计算分段
28+
def split_video(filename, outdir, length=90, overwrite=True):
29+
30+
duration = math.floor(float(get_video_duration(filename)))
31+
part = math.floor(duration / length)
32+
33+
basenames = os.path.basename(filename).split('.')
34+
35+
mainname = basenames[0]
36+
extname = basenames[1]
37+
start = 0
38+
partindex = 1
39+
for i in range(0, part):
40+
outname = os.path.join(outdir, ''.join([mainname, "_", str(partindex), ".", extname]))
41+
if os.path.exists(outname):
42+
if overwrite:
43+
os.remove(outname)
44+
else:
45+
print("文件已生成,跳过")
46+
continue
47+
48+
cut_video(filename, outname, start, length)
49+
start += length
50+
partindex += 1
51+
pass
52+
return partindex
53+
54+
55+
# 获取文件
56+
def main(dir):
57+
outdir = os.path.join(dir, "output")
58+
if not os.path.exists(outdir):
59+
os.mkdir(outdir)
60+
for fname in os.listdir(dir):
61+
fname = os.path.join(dir, os.path.join(dir, fname))
62+
if os.path.isfile(fname):
63+
split_video(fname, outdir)
64+
65+
if __name__ == '__main__':
66+
main(r"D:\Project\marketing\videos")
67+
68+

0 commit comments

Comments
 (0)