#!/usr/bin/python # -*- coding: UTF-8 -*- import os def run_cmd(s_cmd): print (s_cmd) assert ( 0 = = os.system(s_cmd)) def takeFilePathName(filepath): return os.path.basename(filepath) def autoMergeTsFileToMp4(inputDir, outDir): if not os.path.isdir(inputDir): return files = os.listdir(inputDir) tsFiles = [] for file in files: filepath = os.path.join(inputDir, file ) if os.path.isdir(filepath): autoMergeTsFileToMp4(filepath, outDir) else : tsFiles.append(filepath) if len (tsFiles)< = 0 : return tsDirName = os.path.basename(inputDir) tsFileListPath = '{0}.txt' . format (inputDir) if not os.path.isdir(outDir): os.makedirs(outDir) mergeFilePath = os.path.join(outDir, '{0}.mp4' . format (tsDirName)) with open (tsFileListPath, 'w' ) as f: tsFiles.sort(key = takeFilePathName) for filePath in tsFiles: f.write( "file '{0}'\n" . format (filePath)) isTsFile = tsFiles[ 0 ].endswith( '.ts' ) if not isTsFile: return binFfmpeg = 'ffmpeg' s_cmd = '{0} -f concat -safe 0' . format (binFfmpeg) s_cmd + = ' -i {0} -c copy {1}' . format (tsFileListPath,mergeFilePath) run_cmd(s_cmd) def main(): videoRootDir = 'D:\\极客时间\\video-data' outTsDir = os.path.join(videoRootDir, 'outx' , 'ts' ) outMp4Dir = os.path.join(videoRootDir, 'outx' , 'mp4' ) autoMergeTsFileToMp4(outTsDir, outMp4Dir) if __name__ = = '__main__' : main() |