写了个合并小视频的小脚本

2018-10-22 09:34:11 +08:00
 ucun

深夜思考人生的时候会找些资料来格物致知。不过有的资料总是分成若干个小文件。。

按说现在视频播放器都会自动按顺序播放,但中间总会有点小停顿。无赖只好找视频编辑软件合起来。。

更无赖的是大多编辑软件要么收费、要么有水印。

只好请出 ffmpeg 了, 在用 ffmpeg 前,要先对文件名进行排序。按说 sort 命令就好了,但字母数字混合的不好搞。

Google 了一下,也没找到相关命令,只好按需写段小脚本。


#! /usr/bin/env python
# -*- coding:utf-8 -*-

import os
import sys

def getFileList(path):
    fileListTmp = os.listdir(path)
    fileList = []
    for i in fileListTmp:
        if i[-3:] == '.ts':
            fileList.append(i)
    fileList.sort(key=lambda x: int(os.path.splitext(x)[0].split('720p')[1]))
    txt = os.path.join(path,'b.txt')
    with open(txt,'w') as f:
        for i in fileList:
            f.write('file ' + str(path) + '/' + i + '\n')

    f.close()
    return txt

def main():
    path = os.path.abspath(sys.argv[-1])
    txt = getFileList(path)
    outFileName = path.split('/')[-1] + '.mp4'
    output = os.path.join(path,outFileName)
    os.system('ffmpeg -f concat -safe 0 -i ' + txt + ' -c copy ' + output)
    print('Your video file at {}'.format(output))
    os.system('rm ' + txt)

if __name__ == '__main__':
    main()


欢迎留下更好的解决方案。

2980 次点击
所在节点    Python
7 条回复
snowwalf
2018-10-22 09:59:39 +08:00
ant2017
2018-10-22 10:03:38 +08:00
f.close() 是不是多余
lfzyx
2018-10-22 10:22:42 +08:00
这个我一般用 Amazon Elastic Transcoder 处理
est
2018-10-22 10:39:51 +08:00
ffmpeg -f concat -i "list.txt" -vf "select=concatdec_select" out.mp4

大概这样就行。list.txt 格式参考下文档。可以设置每段视频起止时间。
justou
2018-10-22 23:38:32 +08:00
可以看下这个用 cython 包装 ffmpeg 的项目:

http://docs.mikeboers.com/pyav/develop/

https://github.com/mikeboers/PyAV
sb137885
2018-10-23 18:12:46 +08:00
moviepy
c4f36e5766583218
2019-05-10 13:52:08 +08:00
这个可以吗?
sort -V: natural sort of (version) numbers within text

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/499676

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX