baobao
4/16/2018 - 2:50 PM

ts2mp4.py

import urllib.request
import ssl
import sys
import os

ssl._create_default_https_context = ssl._create_unverified_context

args = sys.argv

# 連番部分を%dにする

# python cmd.py 1 10 test https://hoge.com/seg-%d-v1-a1.ts output

FILE_LIST_NAME='temp.txt'



def downloads():
    print("====== downloads ======")
    print('startCnt : ' + str(startCnt) + ' / cnt : ' + str(cnt))
    tempFileList=[]
    # 個数を変更
    for t in range(cnt):
        i = startCnt + t
        url = baseURL % (i)
        dirName = g_saveDirName
        if os.path.exists(dirName) == False:
            os.mkdir(dirName)
        saveName = dirName + '/ts' + str(i) + '.ts'
        print(saveName + " / " + url)
        # fileダウンロード
        fullLocalPath = os.path.abspath(saveName)
        print("fullLocalPath : "+fullLocalPath)
        tempFileList.append("file " + fullLocalPath)
        try:
            urllib.request.urlretrieve(url, saveName)
        except Exception:
            print('You can not do this operation!')
            break;
    return tempFileList

def writeFileList(list):
    print("====== writeFileList ======")
    # 一次ファイルリストText生成
    f = open(g_saveDirName + '/' + FILE_LIST_NAME, 'w') # 書き込みモードで開く
    for item in list:
        f.write(item + "\n") # 引数の文字列をファイルに書き込む
    f.close() # ファイルを閉じる

def convert():
    print("====== convert ======")
    commandName = "ffmpeg -safe 0 -f concat -i %s -c:v copy -c:a copy -c:s copy -map 0:v -map 0:a -map 0:s? %s.mp4" % (g_saveDirName + '/' + FILE_LIST_NAME, g_outputName)
    print(commandName)
    os.system(commandName)
    # TODO 各種ファイル削除
    print("Complete")


mode = int(args[1])

if mode == 1:
    print("MODE : " + str(mode))
    g_saveDirName = args[2]
    g_outputName = args[3]
    convert()
else:
    print("MODE : " + str(mode))
    startCnt = int(args[2])
    cnt = int(args[3])
    g_saveDirName = args[4]
    baseURL = args[5]
    g_outputName = args[6]
    # full
    writeFileList(downloads())
    convert()