TVB电视剧北美、加拿大地区地址(需要翻一下才能看):https://tvbanywherena.com/cantonese
如下为完成代码,通过python获取m3u8,下载音、视频切片,解密,合并。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import m3u8
import os
import requests
import threading
from Crypto.Cipher import AES
def download(download_path, key, vi, url, file_name):
"""
下载分片文件 下载内容需要通过m3u8中EXT-X-KEY解密
:param download_path: 下载文件本地磁盘路径
:param key:EXT-X-KEY
:param vi:IV
:param url: 下载地址
:param file_name:存储文件名
:return:
"""
try:
requests.packages.urllib3.disable_warnings()
res = requests.get(url, stream=True, verify=False)
content_video_part = AES.new(key, AES.MODE_CBC, vi).decrypt(res.content)
ts_path = download_path + "/{}".format(file_name)
with open(ts_path, 'ab') as f: # 追加保存解密结果
f.write(content_video_part)
except Exception as e:
print("异常请求:%s" % e.args)
return
print("TS文件下载完毕!!\n")
def file_filter(f):
if f[-3:] in ['.ts']:
return True
else:
return False
def merge(download_path, hebing_path):
"""
将所以分片合并成一个文件
:param download_path: 分片文件目录
:param hebing_path: 分片文件合并结果目录
:return:
"""
all_ts = os.listdir(download_path)
# 筛选
all_ts = list(filter(file_filter, all_ts))
# 排序
all_ts.sort(key=lambda x: int(x[:-3]))
li_audio = [os.path.join(download_path+"/",filename) for filename in all_ts]
command = 'ffmpeg -i "concat:%s" -codec copy %s' %('|'.join(li_audio), hebing_path)
os.system(command)
print("合并完成!!")
def merge_video_voice(mp4_path, wav_path, path):
"""
将音频和视频文件合并
:param mp4_path:视频文件路径
:param wav_path:音频文件路径
:param path:合并结果路径
:return:
"""
command = 'ffmpeg -i %s -i %s -c copy %s' % (mp4_path, wav_path, path)
print(command)
os.system(command)
print("合并完成!!")
def get_m3u8_info(uri):
"""
:param uri: m3u8 url
:return: 分片url,EXT-X-KEY,IV
"""
play_list = m3u8.load(uri=uri, verify_ssl=False)
key = requests.get(play_list.keys[0].uri, verify=False).content
return play_list.segments, key, bytes.fromhex(play_list.keys[0].iv[2:])
if __name__ == '__main__':
# video master m3u8
mp4_m3u8_url = "";
# voice master m3u8
wav_m3u8_url = "";
# download path
download_path = r"/Users/Desktop/pianzhongchuanqi"
# 合并结果path
hebing_path = r"/Users/Desktop/pianzhongchuanqi"
segments, key, vi = get_m3u8_info(mp4_m3u8_url)
for index, segment in enumerate(segments):
t = threading.Thread(target=download, args=(download_path+"/mp4", key, vi, segment.uri, str(index)+".ts",))
t.start()
while threading.activeCount() !=1:
pass
merge(download_path+"/mp4", hebing_path+"/total.mp4")
segments, key, vi = get_m3u8_info(wav_m3u8_url)
for index, segment in enumerate(segments):
t = threading.Thread(target=download, args=(download_path+"/wav", key, vi, segment.uri, str(index)+".ts",))
t.start()
while threading.activeCount() !=1:
pass
merge(download_path+"/wav", hebing_path+"/total.wav")
# video voice 合并
merge_video_voice(hebing_path+"/total.mp4", hebing_path+"/total.wav", hebing_path+"/final.mp4")
相关剧集m3u8链接获取方式:
注意:该网站需要翻q一下才能过去看,但是m3u8是不需要翻。