【问题标题】:Merging ts video files using Python使用 Python 合并 ts 视频文件
【发布时间】:2016-12-20 21:11:43
【问题描述】:

我正在使用m3u8 Python library 解析m3u8 并将ts 视频文件下载到磁盘中,如下脚本所示:

import m3u8, urllib
playlist = "https://sevenwestmedia01-i.akamaihd.net/hls/live/224853/TEST1/master_lowl.m3u8"

while True:
   m3u8_obj = m3u8.load(playlist)
   ts_segments_str = str(m3u8_obj.segments)
   for line in ts_segments_str.splitlines():
       if "https://" in line:
           ts_id = line[-20:]
           testfile = urllib.URLopener()
           testfile.retrieve(line, ts_id)

是否有不使用 FFmpeg 将 ts 文件合并在一起的 Python 库?

【问题讨论】:

标签: python


【解决方案1】:

如果有必要,你也可以使用我的脚本

import requests
import m3u8
import shutil
import os


def strip_end(text, suffix):
    if not text.endswith(suffix):
        return text
    return text[:len(text)-len(suffix)]


def download_file(url):
    local_filename = url.split('/')[-1]
    # NOTE the stream=True parameter
    r = requests.get(url, stream=True)
    with open(f"ts_files/{local_filename}", 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)

    return local_filename


m3u8_url = 'your m3u8 url goes here'
r = requests.get(m3u8_url)
m3u8_master = m3u8.loads(r.text)
# print(m3u8_master.data['segments'])
m3u8_file = m3u8_url.split('/')[-1]
url = strip_end(m3u8_url, m3u8_file)
url_copy = url

if not os.path.exists('ts_files'):
    print('ts_file folder is not found, creating the folder.')
    os.makedirs('ts_files')

# print statement can be deleted, they were placed prior to debugging purposes.
for seg in m3u8_master.data['segments']:
    print(url)
    url += seg['uri']
    print(url)
    print(f'downloading {seg["uri"]}')
    # download_file(url)  # comment out this line to download ts files.
    url = url_copy
    print(url)
    print()


# you should comment out the rest part if you want to merge your multiple ts files to one ts file.
"""
cwd = os.getcwd()  # Get the current working directory (cwd)
TS_DIR = 'ts_files'
with open('merged.ts', 'wb') as merged:
    for ts_file in os.listdir(f'{cwd}/{TS_DIR}'):
        with open(f'{cwd}/{TS_DIR}/{ts_file}', 'rb') as mergefile:
            shutil.copyfileobj(mergefile, merged)
"""

【讨论】:

    【解决方案2】:
    import sys, urllib2
    import socks
    from sockshandler import SocksiPyHandler
    from urlparse import urlparse
    from urllib import urlopen
    
    i=0
        while i<1000:
            ' url from m3u8
            filename=filename+str(i)+'.ts'
            opener = urllib2.build_opener()
            ts = opener.open(filename).read()
            ' append stream to file
            tsfile = open(file, 'ab')
            tsfile.write(ts)
            print 'part %s done!' % i   
            i=i+1
    

    【讨论】:

    • 请解释答案。
    猜你喜欢
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2019-11-20
    相关资源
    最近更新 更多