I want to record youtube live stream and save it to file using python.
I tried with pytube library but it probably works for videos, not for live streams.
I want to record stream and save it to file with video format as avi or something like this.
I want to record youtube live stream and save it to file using python.
I tried with pytube library but it probably works for videos, not for live streams.
I want to record stream and save it to file with video format as avi or something like this.
Modification based on @wownis 's answer.
(I tried that answer, however, it doesn't work.)
# pip install urllib
# pip install m3u8
# pip install streamlink
import urllib
import m3u8
import streamlink
def get_stream(url):
"""
Get upload chunk url
"""
streams = streamlink.streams(url)
stream_url = streams["best"]
m3u8_obj = m3u8.load(stream_url.args['url'])
return m3u8_obj.segments[0]
def dl_stream(url, filename, chunks):
"""
Download each chunks
"""
pre_time_stamp = 0
for i in range(chunks+1):
stream_segment = get_stream(url)
cur_time_stamp = \
stream_segment.program_date_time.strftime("%Y%m%d-%H%M%S")
if pre_time_stamp == cur_time_stamp:
pass
else:
print(cur_time_stamp)
file = open(filename + '_' + str(cur_time_stamp) + '.ts', 'ab+')
with urllib.request.urlopen(stream_segment.uri) as response:
html = response.read()
file.write(html)
pre_time_stamp = cur_time_stamp
url = "https://www.youtube.com/watch?v=2U3JnFbD-es"
dl_stream(url, "live", 15)
Output like this:
./
live_20200713-103739.ts
live_20200713-103744.ts
...
I found a solution and i put my code in python:
import urllib import m3u8 import streamlink def record_stream(url,filename,iterations): last_part = 0 for i in range(iterations+1): streams = streamlink.streams(url) stream_url = streams["best"] print(stream_url.args['url']) m3u8_obj = m3u8.load(stream_url.args['url']) previous_part_time = last_part last_part = m3u8_obj.segments[-1].program_date_time if i >= 1: for j in range(1, len(m3u8_obj.segments)): if m3u8_obj.segments[-j].program_date_time == previous_part_time: break print(j) file = open(filename + ".ts", "ab+") for i in range(j-1,0,-1): with urllib.request.urlopen(m3u8_obj.segments[-i].uri) as response: html = response.read() file.write(html) url = "https://www.youtube.com/watch?v=BgKGctL0u1U" record_stream(url,"file",10)
10 means 10 iterations if chunks have 2s it means that records 20s of stream