[Python] Screen recorder with python

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to create a screen recording program using Python, but I'm running into some issues. My goal is to be able to set a specific duration (e.g., 10 seconds) and frame rate (e.g., 30 FPS), but my videos either end up being too fast (5x faster than normal) or have bad frame rates.

    Also, the duration is never what I set it to. For example, if I set the duration to 10 seconds, the video is only 6 seconds long.

    Here’s the code I’m currently using, but it's not working as expected:

    import pyautogui
    import cv2
    import numpy as np
    import time

    screen_width, screen_height = pyautogui.size()
    fps = 30
    duration = 10 # Set duration to 10 seconds

    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter('output.avi', fourcc, fps, (screen_width, screen_height))

    start_time = time.time()
    while True:
    screenshot = pyautogui.screenshot()
    frame = np.array(screenshot)
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
    out.write(frame)

    if time.time() - start_time > duration:
    break


    out.release()
    cv2.destroyAllWindows()



    Issues I am facing:

    Video is too fast or has bad frame rate:

    • When I play back the video, it looks either 5x faster or the framerate is too low, even though I set it to 30 FPS.

    Duration mismatch:

    • If I set the duration to 10 seconds, the video only lasts about 6 seconds.

    What I’ve tried:

    • Adjusting the fps value, but that doesn't seem to fix the issue.
    • Changing the video writer codec, but that didn’t help either.
    • Adding a sleep delay between frames, but it didn’t affect the result.

    Continue reading...

Compartilhe esta Página