python脚本录制网上现场直播视频(python script to record online

2019-07-29 01:35发布

我正在开发一个脚本下载在线直播流媒体视频。

我的脚本:

print "Recording video..."
response = urllib2.urlopen("streaming online video url")
filename = time.strftime("%Y%m%d%H%M%S",time.localtime())+".avi"
f = open(filename, 'wb')

video_file_size_start = 0  
video_file_size_end = 1048576 * 7  # end in 7 mb 
block_size = 1024

while True:
    try:
        buffer = response.read(block_size)
        if not buffer:
            break
        video_file_size_start += len(buffer)
        if video_file_size_start > video_file_size_end:
            break
        f.write(buffer)

    except Exception, e:
        logger.exception(e)
f.close()

上面的脚本工作正常,下载从现场直播内容的视频7MB并将其存储在以* .avi文件。

不过,我想下载只需10视频秒,无论文件的大小,并将其存储在AVI文件。

我尝试不同的可能性,但没有成功。

可以在任何一个请在这里分享你的知识来解决我的问题。

提前致谢。

Answer 1:

我不认为有这样做,如果没有不断地分析视频,这将是方式昂贵的任何方式。 所以,你可以利用你需要多少MB猜测和做一次检查它的足够长的时间。 如果它太长,只是削减它。 相反的猜测,你也可以建立你需要多少找回了一些统计数据。 你也可以更换,而真正有:

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

这应该给你的视频至少10秒,除非连接需要太多的时间(小于10秒,然后)或服务器发送更多的缓冲(但不太可能对直播流)。



Answer 2:

您可以使用“内容长度”标头(如果存在)来检索视频文件大小。

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


Answer 3:

response.read()不起作用。 response.iter_content()似乎做的伎俩。

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()


文章来源: python script to record online live streaming videos