如何在 python 中录制 twitch 流,最好使用 livestreamer?

How to record twitch stream in python, preferably using livestreamer?

目前我只有:

from livestreamer import Livestreamer
session = Livestreamer()
stream = session.streams('http://www.twitch.tv/riotgames')
stream = stream['source']
fd = stream.open()

由于我还是 python 的新手,所以我完全不知道接下来该做什么。我如何连续保存,比方说,流的最后 40 秒到文件?

这是一个开始:

from livestreamer import Livestreamer
session = Livestreamer()
stream = session.streams('http://www.twitch.tv/riotgames')
stream = stream['source']
fd = stream.open()
with open("/tmp/stream.dat", 'wb') as f:
    while True:
        data = fd.read(1024)
        f.write(data)

我试过了。例如,您可以在 VLC 中打开 /tmp/stream.dat。该示例将一次读取 1 kb 并将其写入文件。

该程序将永远 运行,因此您必须使用 Ctrl-C 中断它,或为此添加一些逻辑。您可能需要以某种方式处理错误和流的结尾。