当前位置: 首页 > 工具软件 > m3w > 使用案例 >

python实现m3u8转mp4

奚高扬
2023-12-01

python实现m3u8转mp4

需要用到两个版本ffmpeg文件及原码请到项目地址自取
https://gitee.com/z2322739526/m3u8
主要解决ts改后缀mp4无法上传网盘播放的问题,所以需要完整处理下
tomp4.py费时费电脑,转码速度大约6分钟共处理总计5分钟视频
完整代码如下
m3u8.py

import requests
import re
import os
import urllib.parse
import time
import shutil

start_time = time.time()
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',
}
m3u8_url = input("m3u8_url:")
# url解码
m3u8_url = urllib.parse.unquote(m3u8_url)
r_url = '.*&vurl=(.*ver=4)'
url_list = re.findall(r_url,m3u8_url)
if len(url_list) != 0:
    m3u8_url = url_list[0]
if m3u8_url == '1':
    m3u8 = open('14.m3u8').read()
else:
    m3u8 = requests.get(m3u8_url,headers = headers).text
r_m3u8 = ',\n(.*?)\n#'
# re.S整体匹配
ts_all = re.findall(r_m3u8,m3u8,re.S)
print(ts_all[:10])
print('共 %d 个ts文件'%len(ts_all))
# 删除之前ts
if os.path.exists('./ts'):
    shutil.rmtree('./ts')
    os.mkdir('./ts')
if not os.path.exists("./ts"):
    os.mkdir("./ts")
num = 0
for ts_2 in ts_all:
    try:
        ts = requests.get(ts_2,headers = headers).content
        np = (len(str(len(ts_all)))-len(str(num)))*'0'+str(num)
        with open('./ts/%s.ts'%np,'wb') as fp:
            fp.write(ts)
        print('%s.ts save'%np)
        num += 1
    except:
        # https://jx.parwix.com:4433/player/?url=https://www.iqiyi.com/v_dql4i2lz0c.html?vfm=2008_aldbd&fv=p_02_01
        # 解析系统特化链接
        ts_2 = 'https://211.99.101.171:4433' + ts_2
        ts = requests.get(ts_2,headers = headers).content
        np = (len(str(len(ts_all)))-len(str(num)))*'0'+str(num)
        with open('./ts/%s.ts'%np,'wb') as fp:
            fp.write(ts)
        print('%s.ts save'%np)
        num += 1
end_time = time.time()
print('下载完成,总耗时:',end_time-start_time) 
# https://sod.bunediy.com/20211217/njayYgPt/index.m3u8  

tomp4.py

import sys
import os
import time

start_time = time.time()

def getmax(file_dir):
    for root, dirs, files in os.walk(file_dir):
        return len(files[0])-3
        break

print(sys.path[0])
start = int(input('请输入起始数字:'))
num = len(os.listdir("./ts"))
fmax = getmax("./ts")
print('最大长度', fmax)

for i in range(start,num):
    name = (fmax - len(str(i)))*'0' + str(i)
    print('正在处理', name)
    os.system("ffmpeg-old -i " + sys.path[0] + r"\ts\%s.ts -threads 2 "%name + sys.path[0] + "\mp4\%s.mp4"%name)
      

names = os.listdir("./mp4")      
print(names)
fp = open('./list.txt','w')
for i in names:
    fp.write("file 'mp4/%s'\n"%i)
fp.close()

end_time = time.time()
print('下载完成,总耗时:',end_time-start_time) 
os.system('pause')

合并mp4.bat

ffmpeg-new -f concat -i list.txt -c copy out.mp4
pause
 类似资料: