python 练习~文件解析及下载

ffmpeg 用于视频文件合并,由于本地安装有问题导致无法在python中使用,代码最后会打印ffmpeg视频文件合并命令,拷贝命令至终端执行即可

Requests

import re
import requests
import ffmpy3

prefix_path = '/m3u8/'
source_path = prefix_path + 'index.m3u8'
target_file = prefix_path + 'other.m3u8'
key_file_name = 'key.m3u8'
base_url = 'http://IP:PORT'

def parseM3u8File(file_path):
    with open(file=file_path, mode='r', encoding='UTF-8') as f:
        lines = f.readlines()

    newFileContent = []
    for line in lines:
        parseLine(line)
        replaceM3u8Content(line, newFileContent)
    generateNewM3u8(newFileContent)


def parseLine(lineContent):
    pattern_0 = r'#EXT-X-KEY:METHOD=(.*?),URI="(.*?)"'
    pattern_1 = r'(.*?\.ts)'

    matchObj = re.match(pattern_0, lineContent, re.I)
    if matchObj:
        uri = matchObj.group(2)
        download_key(uri)
    else:
        matchObj = re.match(pattern_1, lineContent, re.I)
        if matchObj:
            download_file(matchObj.group(1))


def replaceM3u8Content(raw, newFileContent):

    pattern_0 = r'#EXT-X-KEY:METHOD=AES-128,URI="(.*?)"'
    pattern_1 = r'.*/(.*?\.ts)'

    matchObj = re.match(pattern_0, raw, re.I)
    if matchObj:
        newFileContent.append('#EXT-X-KEY:METHOD=AES-128,URI="' +
                              key_file_name + '"\n')
    else:
        matchObj = re.match(pattern_1, raw, re.I)
        if matchObj:
            newFileContent.append('video/'+matchObj.group(1) + "\n")
        else:
            newFileContent.append(raw)


def generateNewM3u8(newFileContent):
    with open(target_file, mode='w', encoding='UTF-8') as f:
        f.writelines(newFileContent)


def download_key(keyFileUri):
    keyData = requests.get(base_url+keyFileUri).content
    with open(prefix_path + key_file_name, mode='wb') as f:
        f.write(keyData)


def download_file(url):
    pattern_1 = r'.*/(.*?\.ts)'
    matchObj = re.match(pattern_1, url, re.I)
    video_data = requests.get(base_url+url).content
    fileNmae = matchObj.group(1)
    with open(prefix_path +"video/"+ fileNmae, mode='wb') as f:  # 保存数据
        f.write(video_data)
        print('download finised ....\n')


parseM3u8File(source_path)


ff = ffmpy3.FFmpeg(
    inputs={ target_file: '-allowed_extensions ALL'},
    outputs={ prefix_path+ 'all.mp4' : '-c copy'})
print(ff.cmd)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值