|
| 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