python将ts转换成MP4

代码可以直接运行。

# -*- coding: utf-8 -*-

from urllibimport request

import os

from multiprocessingimport Pool

from globimport glob

def run(i):

url ="https://hong.tianzhen-zuida.com/20191220/16480_107655d7/1000k/hls/3564346f72c00000"+str(i)+".ts"

    print("开始下载:"+url)

headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36"}

r = request.Request(url, headers = headers)

# print(r.content)

    try:

downloaded_file =open('./mp4/{}'.format(url[-10:]),'wb')

req = request.Request(url, headers={'User-Agent':'Mozilla/5.0'})

file_on_web = request.urlopen(req)

print("downloading...")

while True:

buf = file_on_web.read(65536)

if len(buf) ==0:

break

            downloaded_file.write(buf)

downloaded_file.close()

file_on_web.close()

print("done")

except request.ContentTooShortError:

print('Network conditions is not good.Reloading.')

else:

return ""

# 对转换的TS文件进行排序

def get_sorted_ts(user_path):

ts_list = glob(os.path.join(user_path, '*.ts'))

boxer = []

for tsin ts_list:

if os.path.exists(ts):

# print(os.path.splitext(os.path.basename(ts)))

            file, _ = os.path.splitext(os.path.basename(ts))

print(int(file.replace("c", "")))

boxer.append(int(int(file.replace("c", ""))))

boxer.sort()

print(boxer)

return boxer

# 文件合并

def convert_m3u8(boxer, o_file_name):

# cmd_arg = str(ts0)+"+"+str(ts1)+" "+o_file_name

    tmp = []

for tsin boxer:

print(ts)

tmp.append("mp4\\c00000" +str(ts) +'.ts')

cmd_str ='+'.join(tmp)

exec_str ="copy /b " + cmd_str +' ' +" mp4\\" + o_file_name

print(exec_str)

res = os.popen(exec_str)

print(res.read())

if __name__ =='__main__':

# 创建进程池,执行10个任务

    print("开始执行")

pool = Pool(10)

for iin range(10):

pool.apply_async(run, (i,))#执行任务

    pool.close()

pool.join()

print('下载完成!')

user_path ="E:\\code\\Python\\mp4\\"

    o_file_name ="庆余年第一季(2019)第46集.mp4"

    boxer = get_sorted_ts(user_path)

convert_m3u8(boxer,o_file_name)

os.system('del /Q mp4\\*.ts')

print("删除文件")

print('ok!处理完成')

你可能感兴趣的:(python将ts转换成MP4)