当前位置: 代码网 > it编程>前端脚本>Python > python实现将m3u8视频转换成mp4的操作步骤

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

2024年06月11日 Python 我要评论
首先,网上获取m3u8视频第一种,浏览器控制面板下,定位的sources的tab, 在右侧的xhr/fetch breakpoints下添加过滤,如下图所示,如果它访问的网络有对应的过滤条件,会断点暂

首先,网上获取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的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com