python根据m3u8索引文件合并ts文件

import os
import threading
import time
def read_file():
    f=open('C://Users/asus/Desktop/Moc_1206591210_1213896655_-1/Moc_1206591210_1213896655_-1.m3u8')
    text_list=f.readlines()
    files = []
    print(text_list)
    for i in text_list:
        if i.find('#EX')==-1: #有#EXfind返回0,无-1
            files.append(i)
    f.close()
    tmp = []
    for file in files[0:len(files)]:
        tmp.append(file.replace("\n",""))
    os.chdir("C://Users/asus/Desktop/Moc_1206591210_1213896655_-1")  # 用于改变当前工作目录到指定的路径
    shell_str = '+'.join(tmp)
    return shell_str


def thread(shell_str):
    time.sleep(2)
    # windows窗口命令——(copy/b)文件无缝拼接隐藏
    shell_str = 'copy /b ' + shell_str + ' 1.mp4'
    # os模块中的system()函数可以方便地运行其他程序或者脚本
    os.system(shell_str)
    print('---子线程结束---')


if __name__ == "__main__":
    shell_str=files=read_file()
    t1 = threading.Thread(target=thread(shell_str))
    t1.setDaemon(True)
    t1.start()
    t1.join(timeout=1)#不填就是等待子线程结束
### 使用Python实现m3u8文件的爬取与处理 #### 1. m3u8 文件简介 M3U8 是一种基于 HTTP 的流媒体传输协议,通常用于在线视频播放。它通过一个索引文件(即 `.m3u8` 文件),指向多个分片的小文件(通常是 TS 格式的片段)。这些片段会被客户端逐个加载并拼接成完整的视频。 为了完成 Python 爬取和处理 M3U8 文件的任务,需要遵循以下逻辑流程: - **获取目标页面中的 M3U8 链接**:分析 HTML 页面结构找到对应的 M3U8 地址[^1]。 - **解析 M3U8 文件内容**:提取其中的所有 TS 片段地址[^2]。 - **下载 TS 文件合并为 MP4**:逐一下载 TS 文件并将它们按顺序组合成最终的视频文件[^3]。 --- #### 2. 实现代码示例 以下是完整的 Python 脚本,展示如何从指定 URL 中抓取 M3U8 文件,并将其转换为本地 MP4 文件。 ```python import os import requests from Crypto.Cipher import AES from concurrent.futures import ThreadPoolExecutor def fetch_m3u8(url, headers=None): """ 获取 M3U8 文件 """ response = requests.get(url, headers=headers) if response.status_code != 200: raise Exception(f"M3U8 请求失败: {response.status_code}") return response.text.strip() def parse_ts_urls(m3u8_content, base_url=""): """ 解析 M3U8 文件以获得所有 TS 文件的 URL 列表 """ ts_urls = [] lines = m3u8_content.splitlines() for line in lines: if not line.startswith("#") and ".ts" in line: full_url = f"{base_url}{line}" if not line.startswith("http") else line ts_urls.append(full_url) return ts_urls def download_file(url, save_path, key=None): """ 下载单个 TS 文件并解密 (如果存在加密) """ try: res = requests.get(url, stream=True) content = res.content if key is not None: # 如果存在加密,则先解密数据 cipher = AES.new(key, AES.MODE_CBC, iv=bytes([0] * 16)) content = unpad(cipher.decrypt(content), AES.block_size) with open(save_path, 'wb') as f: f.write(content) except Exception as e: print(f"[Error] Download failed: {url}, Error: {e}") def merge_files(ts_list, output_filename): """ 将多个 TS 文件合并为单一 MP4 文件 """ with open(output_filename, 'wb') as merged: for ts_part in sorted(ts_list): # 按序号读取部分文件 with open(ts_part, 'rb') as part: merged.write(part.read()) print(f"\n[Info] Video saved to '{output_filename}'") if __name__ == "__main__": video_url = input("请输入视频播放页URL或直接输入M3U8链接: ").strip() # Step 1: Fetch the initial M3U8 file headers = {"User-Agent": "Mozilla/5.0"} m3u8_text = fetch_m3u8(video_url, headers=headers)[^1] # Step 2: Parse all .ts URLs from the M3U8 file base_dir = "/".join(video_url.split("/")[:-1]) + "/" ts_links = parse_ts_urls(m3u8_text, base_dir) # Optional: Handle encryption keys if present in M3U8 (#EXT-X-KEY directive) aes_key = None # 假设未加密;如果有加密则需额外解析 KEY 字段 # Step 3: Create a directory & start downloading each segment concurrently temp_folder = "./temp_segments/" os.makedirs(temp_folder, exist_ok=True) downloaded_parts = [] with ThreadPoolExecutor(max_workers=10) as executor: futures = [ executor.submit( download_file, url=url, save_path=f"{temp_folder}/{idx}.ts", key=aes_key ) for idx, url in enumerate(ts_links) ] for future in futures: result = future.result() # Wait until completion of downloads if result is not None: downloaded_parts.append(result) # Step 4: Merge segments into final MP4 file output_video_name = "final_output.mp4" merge_files(downloaded_parts, output_video_name) ``` --- #### 3. 关键点说明 - **多线程加速下载**: 使用 `ThreadPoolExecutor` 并发下载多个 TS 文件,提升效率。 - **AES 加密支持**: 若 M3U8 文件涉及加密 (`#EXT-X-KEY`),可以通过解析其字段获取解密所需的 Key 和 IV 参数。 - **错误处理机制**: 对于网络异常或其他潜在问题进行了基本捕获,确保程序稳定性。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值