video-streamingtwitch

Downloading a live Twitch stream


I'm looking for a way to "pipe" (sorry if I'm butchering the terminology here) a Twitch stream into a file as it is being streamed. I know it is possible to download the VODs after the stream is done but that is not applicable in my use case.

Ive had a look at a library called streamlink which would allow me to get the exact url of a given stream but I'm kind of lost as to where to go from here


Solution

  • Here's a solution that worked for me:

    Firstly, install Streamlink. Then just run this command

    streamlink -o <file name>.mkv <URL of the Twitch stream> best

    to save the stream to local file.

    If you want to achieve this programmatically you can use the Streamlink pip module (pip install streamlink) in conjuction with ffmpeg.

    Here's what the code might look like (in Python 3):

    import streamlink
    from subprocess import Popen
    from time import sleep
    
    # get the URL of .m3u8 file that represents the stream
    stream_url = streamlink.streams('https://www.twitch.tv/forsen')['best'].url
    print(stream_url)
    
    # now we start a new subprocess that runs ffmpeg and downloads the stream
    ffmpeg_process = Popen(["ffmpeg", "-i", stream_url, "-c", "copy", 'stream.mkv'])
    
    # we wait 60 seconds
    sleep(60)
    
    # terminate the process, we now have ~1 minute video of the stream
    ffmpeg_process.kill()