我想录制youtube实时流并使用python将其保存到文件中。
我尝试使用pytube库,但它可能适用于视频,而不适用于实时流。
我想记录流并将其保存为avi或类似视频格式的文件。
答案 0 :(得分:0)
我找到了一个解决方案,并将代码放在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)
如果块有2s,则10表示10次迭代,这意味着记录20s的流
答案 1 :(得分:0)
根据@wownis的答案进行修改。
(我尝试过该答案,但是它不起作用。)
# 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)
输出如下:
./
live_20200713-103739.ts
live_20200713-103744.ts
...