Python script for recording live online video

I am developing a script to download live online video.

My Script:

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

The above script works great to download 7Mb video from streaming content and save it in * .avi files.

However, I would like to upload just 10 seconds of video regardless of file size and save it in an avi file.

I tried different possibilities, but to no avail.

Can someone please share your knowledge here to fix my problem.

Thanks in advance.

+5
source share
3 answers

, , . , , MB , , . , . , , , . True :

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

10 , ( 10 ), ( ).

+1

Content-Length , .

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

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

All Articles