V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ucun
V2EX  ›  Python

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

  •  
  •   ucun · 2018-10-22 09:34:11 +08:00 · 2927 次点击
    这是一个创建于 1984 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

    只好请出 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()
    
    
    

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

    7 条回复    2019-05-10 13:52:08 +08:00
    ant2017
        2
    ant2017  
       2018-10-22 10:03:38 +08:00
    f.close() 是不是多余
    lfzyx
        3
    lfzyx  
       2018-10-22 10:22:42 +08:00
    这个我一般用 Amazon Elastic Transcoder 处理
    est
        4
    est  
       2018-10-22 10:39:51 +08:00
    ffmpeg -f concat -i "list.txt" -vf "select=concatdec_select" out.mp4

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

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

    https://github.com/mikeboers/PyAV
    sb137885
        6
    sb137885  
       2018-10-23 18:12:46 +08:00
    moviepy
    c4f36e5766583218
        7
    c4f36e5766583218  
       2019-05-10 13:52:08 +08:00
    这个可以吗?
    sort -V: natural sort of (version) numbers within text
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1001 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:04 · PVG 06:04 · LAX 15:04 · JFK 18:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.