最新消息:重新回归WordPress,我要比较认真的开始更新我的博客了。

python+ffmpeg判断视频编码并转码

我的作品 hanlei 3879浏览

nas上面装了emby,在线播放只支持h264,非h264格式会自动在线转码,但是nas那性能,卡的看不成。所以就想把下载的非h264的视频文件全部转成h264编码。

在linux上想要快速、简单的实现一个功能,第一个想到的就是python。下面附上代码。是新手一边百度一边写的。

和批量改文件名的代码整合成了一个命令行开具

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

import os
import re
import os
import argparse
import subprocess as sp
#==================================================================
def make_argparse():
    ''' change this function for custom command line parameter.'''

    parser = argparse.ArgumentParser()

    # positional argument : parse by sequance , must be exist, 
    # must in right type , must in right sequance
    parser.add_argument("fun", help="要执行的程序。")          #default type is string
    parser.add_argument("path",  help="要处理的路径。") #custorm int type

    # optional argument : parse by key and value, no care 
    # to sequance , such as "-x=xxxx" or "-x xxxx"
    parser.add_argument("-o", "--output",  help="--------")
    parser.add_argument("-old", "--oldname",  help="原文件名格式")
    parser.add_argument("-new", "--newname",  help="新文件名格式")
    parser.add_argument("-v", "--verbosity", help="--------", action="store_true")
    #This means that, if the option is specified, assign the value True to args.verbosity.
    # Not specifying it implies False.

    args = parser.parse_args()
    return args
#==================================================================

def rename(args):
    if(not args.oldname or not args.newname):
        print("需要输入原文件名(-old)和新文件名(-new)格式!\n字符串前置$输入转义字符")
        exit()
    path=os.path.abspath(args.path)
    old=args.oldname
    new=args.newname
    files=os.listdir(path)
    for item in files:
        if item.count('.')>=1:
            #print item
            oldname=path + '/' + item
            reobj=re.search(old,item)
            if(reobj):
                num=1
                if new.count('.')==0:
                    newname=path + '/' + new + '.' + item.split('.')[-1]
                else:
                    newname=path + '/' + new
                for part in reobj.groups():
                    #print part
                    newname=newname.replace('('+str(num)+')',str(part))
                    num=num + 1
                if(not os.path.isfile(newname)):
                    os.rename(oldname,newname)
                print(oldname + '======>'+ newname+'\n')
            else:
                print oldname + "匹配失败!"

#==================================================================

def recode(args):
    path=os.path.abspath(args.path) 
    f=os.listdir(path)
    for fi in f:
        if fi.count('.')>=1:
            oldname=path + '/' + fi
            newnameParts=fi.split('.')
            name_part1=fi[0:fi.rfind('.')]
            name_part2=fi[fi.rfind('.'):]
            newname=path + '/new_' + name_part1 + '.mp4'
            newname=newname.replace(' ','\ ')
            oldname=oldname.replace(' ','\ ')
            p = sp.Popen('ffmpeg -i ' + oldname, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
            (o, e) = p.communicate()
            print(fi)
            fileinfo=(e if(len("".join(o.split()))==0) else 0)
            reobj=re.search(ur'Video:\s(\w+)[\s|,]', fileinfo)
            if(reobj):
                print(reobj.group(1))
                #continue
                #if(reobj.group(1)!='h264' and not os.path.isfile(path+ 'new_' +fi)):
                if(name_part2!='.mp4' and not os.path.isfile(newname)):
                    if(reobj.group(1)=='h264'):
                        sp.call('ffmpeg -i ' + oldname + ' -acodec copy -vcodec copy ' + newname, shell=True)
                    else:
                        sp.call('ffmpeg -i ' + oldname + ' -vcodec h264 -maxrate 2000k ' + newname, shell=True)
                if(os.path.isfile(newname)):
                    os.remove(path + '/' + fi)
                    os.rename(newname,name_part1 + '.mp4')

#main code
args = make_argparse(); 
if args.fun:
    exec(args.fun + "(args)")

转载请注明:HANLEI'BLOG » python+ffmpeg判断视频编码并转码