我使用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)
是否有一个Python库可以在不使用FFmpeg的情况下将ts文件合并在一起?
答案 0 :(得分:0)
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
答案 1 :(得分:0)
如有必要,您也可以使用我的脚本
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)
"""