m3u8文件下载合并的一种方法

现在很多视频网站都把整个视频文件拆分成一个个视频流文件(ts),这些视频流文件的下载地址会放在一个文件中,通常叫做*.m3u8。
我们要想下载整个视频文件可以先把这些视频片段下载下来,然后进行拼接,合成一个大的视频文件。
最先想到的一个想法就是用迅雷的批量下载,如下图所示:


但是这样会存在一个问题,因为下载视频后还有进行视频的合并,所以视频的文件名必须是以一定的顺序进行排序才好合并,事实是文件名大多是乱序的,这很限制操作,你总不能一个一个去吧?

由于本人水平不佳,想了两三天才想到好的解决方法,就是用python调用aria2进行下载(其实是花了两三天才找到python调用aria2的方法,网上一直没教程,最后是去官方文档那里找到的教程,地址如下:https://aria2.github.io/manual/en/html/aria2c.html ),教程中提到:
这是python2的用例,本人用的是python3,根据官方文档中的思路其实是给'http://localhost:6800/jsonrpc' 发送一个请求,在python3中应该用requests.post()方法来实现。
但是遗憾的是,官方文档中并没有给出如何修改任务的名称,只是教了你如何新建任务。
我们知道,aria2有一个webUI的界面, http://aria2c.com/,在新建任务时通过抓包发现这样一个语句,这个语句是post的数据:

[{"jsonrpc":"2.0","method":"aria2.addUri","id":1,"params":[["http://aria2c.com/"],{"out":"12.html","split":"5","max-connection-per-server":"16","seed-ratio":"0"}]}]:


很熟悉对不对,比教程中多了这么一项 "out":"12.html","split":"5","max-connection-per-server":"16","seed-ratio":"0"  nice baby!
我们就加这一句就OK啦!
下面是我的代码,运行前确保你电脑安装了requests库还有aria2:

# -*- coding: utf-8 -*-
"""
Created on Wed Mar 14 15:09:14 2018


@author: Y
"""


import requests
import json


#m3u8的文件路径
path = input("Enter m3u8 file path:").replace('\\','/')
print(path)
file = open(path,'r')
operation = input("是否要加上前缀?y/n\n").strip()
pre_link = ''
if operation == 'y':
    pre_link = input("请输入前缀:").strip()
links = []
for i in file:
    if '#' not in i:
        i = i.strip()
        links.append(pre_link+i)
file.close()
l = len(links)
print("总共有%d个片段..."%l)
length = len(str(len(links)))
n = 0
txt = ""
for link in links:
    n = n + 1
    print("还剩%d个片段未下载..."%(l-n))
    if len(str(n)) < length:
        name = '0'*(length-len(str(n))) + str(n) + ".ts"
    else:
        name = str(n)+".ts"
    txt = txt + "file \'" + name + "\'\n"
    jsonreq = json.dumps({'jsonrpc':'2.0', 'id':1,
               'method':'aria2.addUri',
               'params':[[link],{"out":name,"split":"5","max-connection-per-server":"16","seed-ratio":"0"}]})
    c = requests.post('http://localhost:6800/jsonrpc', jsonreq)
file = open("E:\\aria2data\\filelist.txt","w")
file.write(txt)
file.close()


nice baby!
代码https://github.com/xyy55/Python/blob/master/python3/download_video.py
生成的ts文件用ffmpeg合并,命令行输入:ffmpeg -f concat -safe 0 -i filelist.txt -c copy output.ts

猜你喜欢

转载自blog.csdn.net/xyyxyy55/article/details/80486989