python实现将m3u8视频转换成mp4的操作步骤

m3u8 是一种基于文本的媒体播放列表文件格式,通常用于指定流媒体播放器播放在线媒体流,MP4是一种基于MPEG-4 Part 12(2015)和MPEG-4 Part 14标准的数字多媒体容器格式,本文将给大家介绍python实现将m3u8视频转换成mp4的操作步骤,需要的朋友可以参考下

首先,网上获取m3u8视频
第一种,浏览器控制面板下,定位的Sources的tab, 在右侧的XHR/fetch Breakpoints下添加过滤,如下图所示,如果它访问的网络有对应的过滤条件,会断点暂停,此时可以获取到ts文件

第二种,浏览器控制面板下,定位到Network的tab,下面子集的tab选中Fetch/XHR, 同时在搜索框输入'ts',如下图所示,重新刷新浏览器,如果接口访问存在对应的过滤条件,列表中会有对应的访问接口

其次,将m3u8视频转换成各个ts文件
第一步,我们通过python的requests请求m3u8链接,它会返回文件的内容,m3u8的数据结构如下图所示。具体每个表示什么意思,网上都可以搜,不具体介绍。主要关心我们需要的各个ts。我们通过“\n”将内容分开,会发现ts的前面是不带“#”号的

根据自己的情况,ts的链接拼完整,通过requests将获取到的内容保存到本地。这里采用并行的方式(asyncio + aiohttp), 将所有的ts下载列表放在asyncio.gather中,aiohttp去请求远程ts,达到并行下载的效果

import requests
import os
import asyncio
import aiohttp
dirname = 'tsLib'
if not os.path.exists(dirname):
    os.mkdir(dirname)
 
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36'}
 
async def download_ts(session, url, name):
    async with session.get(url, headers=headers) as response:
        data = await response.read()
        with open(os.path.join(dirname, name+'.ts'), mode='wb') as f:
            f.write(data)
 
async def analysis_m3u8(data):
    filtered_content = data.split("\n")
    tasks = []
    async with aiohttp.ClientSession() as session:
        for index, line in enumerate(filtered_content):
            if not line.startswith('#'):
                url = f'https://c-vod.hw-cdn.xiaoeknow.com/522ff1e0vodcq1252524126/9f5770b41397757889226643080/{line}'
                name = line.split('.')[0]
                print(name, 'namename')
                tasks.append(download_ts(session, url, name))
        await asyncio.gather(*tasks)
        print("Downloads completed.")
 
def get_m3u8(url):
    response = requests.get(url=url, headers=headers)
    m3u8_data = response.text
    return m3u8_data.strip()
 
async def main():
    m3u8_url = "https://c-vod.hw-cdn.xiaoeknow.com/522ff1e0vodcq1252524126/9f5770b41397757889226643080/playlist_eof.m3u8?sign=e6575d5fa9576eedbbc505cd53ca9ab5&t=66296146&us=xicXbvVMwn"
    m3u8_data = get_m3u8(m3u8_url)
    await analysis_m3u8(m3u8_data)
 
asyncio.run(main())

最后,将ts文件合并为mp4文件
这里主要采用ffmpeg方式将ts合并为mp4, 但因为上面下载的顺序按照ts名字来的,不一定有顺序。所以我采用将m3u8获取文件的顺序、数组存储,然后合并ts

import os
import subprocess
 
import requests
 
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36'}
 
 
def get_m3u8(url):
    response = requests.get(url=url, headers=headers)
    m3u8_data = response.text
    return m3u8_data.strip()
 
def getFiles():
    m3u8_url = "https://c-vod.hw-cdn.xiaoeknow.com/522ff1e0vodcq1252524126/9f5770b41397757889226643080/playlist_eof.m3u8?sign=e6575d5fa9576eedbbc505cd53ca9ab5&t=66296146&us=xicXbvVMwn"
    m3u8_data = get_m3u8(m3u8_url)
    filtered_content = m3u8_data.split("\n")
    files = []
    for index, line in enumerate(filtered_content):
        if not line.startswith('#'):
            name = line.split('.')[0]
            files.append(f'{name}.ts')
    return files
 
def merge_ts_to_mp4(ts_dir, output_mp4):
    files = getFiles()
    # Sort the filenames based on the numbers after the underscore
    ts_files = [f for f in files if f.endswith('.ts')]
    ts_paths = [os.path.join(ts_dir, f) for f in ts_files]
    print(ts_paths, '00999')
    # Generate a list of arguments for ffmpeg command
    ffmpeg_args = ['ffmpeg', '-i', 'concat:' + '|'.join(ts_paths), '-c', 'copy', output_mp4]
 
    # Run ffmpeg command
    subprocess.run(ffmpeg_args)
 
    print("Merged all .ts files into", output_mp4)
 
# Example usage:
ts_dir = 'tsLib'
output_mp4 = 'merge_ts.mp4'
 
 
 
merge_ts_to_mp4(ts_dir, output_mp4)

以上就是python实现将m3u8视频转换成mp4的操作步骤的详细内容,更多关于python m3u8转mp4的资料请关注vb.net教程C#教程python教程SQL教程access 2010教程Visual Basic 2010 2012 2013 从入门到精通|xin3721自学网

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值