python script to record online live streaming videos

一曲冷凌霜 提交于 2019-12-02 19:47:11

I don't think there is any way of doing that without constantly analysing the video, which will be way to costly. So you could take a guess of how many MB you need and once done check it's long enough. If it's too long, just cut it. Instead of guessing you could also build up some statistics of how much you need to retrieve. You could also replace the while True with:

start_time_in_seconds = time.time()
time_limit = 10
while time.time() - start_time_in_seconds < time_limit:
    ...

This should give you at least 10 seconds of video, unless connecting takes too much time (less then 10 seconds then) or server sends more for buffering (but that's unlikely for live streams).

You can use the 'Content-Length' header to retrieve the video filesize if it exists.

video_file_size_end = response.info().getheader('Content-Length')

response.read() does not work. response.iter_content() seem to do the trick.

import time
import requests


print("Recording video...")
filename = time.strftime("/tmp/" + "%Y%m%d%H%M%S",time.localtime())+".avi"
file_handle = open(filename, 'wb')
chunk_size = 1024

start_time_in_seconds = time.time()

time_limit = 10 # time in seconds, for recording
time_elapsed = 0
url = "http://demo.codesamplez.com/html5/video/sample"
with requests.Session() as session:
    response = session.get(url, stream=True)
    for chunk in response.iter_content(chunk_size=chunk_size):
        if time_elapsed > time_limit:
            break
        # to print time elapsed   
        if int(time.time() - start_time_in_seconds)- time_elapsed > 0 :
            time_elapsed = int(time.time() - start_time_in_seconds)
            print(time_elapsed, end='\r', flush=True)
        if chunk:
            file_handle.write(chunk)

    file_handle.close()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!