Home > database >  Save video via python on windows logoff
Save video via python on windows logoff

Time:06-08

I am using this code to capture everything on my monitor and save it to mp4 file:

# screen recording config
sct = mss()
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(recording_file_name_location, fourcc, 20.0, (1920, 1080))

# while loop that captures the while screen image by image
while True:
    sct_img = sct.grab(screen_resolution)
    out.write(np.array(sct_img))

The problem is I want this code to stop recording once I logoff from my Windows machine, that does happen, and the video is saved on my Desktop, but it is not playable.

If I run this code via PyCharm and I end the code via PyCharm (CTRL C or I use PyCharm stop button), then it does save the mp4 file and I can play it without any problems.

Also, if I start the code from the CMD it works fine, but if I close CMD windows on the "X" in the top right corner, video is again unplayable.

I guess that this happens due to killing Python process in the background, so the script/code never saves the file properly.

Do you guys have any suggestion for this problem? How to save the mp4 video once I logoff or turn off my Windows machine?

Thank you in advance

CodePudding user response:

The process was killed abruptly.

The video is not playable because out.release() could not be called. Tthe video writer was not given the chance to write index structures into the video file, which can only be done when the file is complete.

Simple fix: make a .ts file instead of any other format/extension. These "transport stream" formats never need finalizing.

Perhaps you need to learn about how Windows ends processes when you log off. Usually Windows sends each application/window a WM_QUERYENDSESSION and WM_ENDSESSION message, telling it to end itself before it gets ended by force.

  • Related