[Python] What's wrong w/ my screen recording script?

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I'm having trouble creating a functioning script to record my screen using python. This is what I have right now:

    import numpy as np
    import cv2
    import pyautogui
    import time
    import os
    import subprocess

    # Get screen size
    screen_size = (1920, 1080)
    print(f"Recording at resolution: {screen_size[0]}x{screen_size[1]}")

    # First create a temporary AVI file
    temp_avi = "temp_recording.avi"

    # Use MJPG codec which is more reliable than XVID
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    fps = 30.0

    # Create the video writer
    out = cv2.VideoWriter(temp_avi, fourcc, fps, screen_size)

    if not out.isOpened():
    print("Failed to initialize VideoWriter")
    exit(1)

    # Variables for tracking
    frames_captured = 0
    start_time = time.time()
    duration = 15 # Record for 15 seconds by default

    print(f"Starting {duration}-second recording...")
    print("Recording will automatically stop after the set duration")

    try:
    # Main recording loop
    while time.time() - start_time < duration:
    # Capture screenshot
    img = pyautogui.screenshot()

    # Convert to numpy array
    frame = np.array(img)

    # Convert from RGB to BGR (very important)
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

    # Write the frame
    out.write(frame)
    frames_captured += 1

    # Display progress
    elapsed = time.time() - start_time
    if int(elapsed) != int(elapsed - 0.1):
    print(f"Recording: {int(elapsed)}/{duration} seconds ({frames_captured} frames)")

    # Small delay to control frame rate
    time.sleep(1/fps)

    print("\nRecording completed!")

    except Exception as e:
    print(f"Error during recording: {e}")

    finally:
    # Properly release resources
    out.release()
    cv2.destroyAllWindows()

    # Check if temp file was created successfully
    if os.path.exists(temp_avi) and os.path.getsize(temp_avi) > 1000:
    print(f"Temporary AVI file created: {temp_avi} ({os.path.getsize(temp_avi)/1024/1024:.2f} MB)")

    # Convert to QuickTime compatible format using FFMPEG if available
    try:
    output_mp4 = "screen_recording.mp4"

    # Check if ffmpeg is available
    try:
    # Use ffmpeg to convert to a QuickTime compatible format
    cmd = [
    "ffmpeg", "-y", # Overwrite output files
    "-i", temp_avi, # Input file
    "-c:v", "libx264", # Use H.264 codec
    "-preset", "fast", # Encoding speed/compression tradeoff
    "-pix_fmt", "yuv420p", # Pixel format (important for compatibility)
    "-movflags", "+faststart", # Optimize for web playback
    output_mp4 # Output file
    ]

    print("Converting AVI to QuickTime-compatible MP4...")
    result = subprocess.run(cmd, capture_output=True, text=True)

    if os.path.exists(output_mp4) and os.path.getsize(output_mp4) > 1000:
    print(f"Conversion successful! MP4 file created: {output_mp4}")
    print(f"File size: {os.path.getsize(output_mp4)/1024/1024:.2f} MB")
    print("This file should be compatible with QuickTime Player")
    else:
    print("Conversion failed. FFMPEG output:")
    print(result.stdout)
    print(result.stderr)

    except FileNotFoundError:
    print("FFMPEG not found. Cannot convert to MP4 format.")
    print("You can still try opening the AVI file with VLC or another player.")
    print("To install FFMPEG, visit: https://ffmpeg.org/download.html")

    except Exception as e:
    print(f"Error during conversion: {e}")

    else:
    print("Error: Recording failed to create a valid file")
    if os.path.exists(temp_avi):
    print(f"File exists but size is only {os.path.getsize(temp_avi)} bytes")
    else:
    print("No output file was created")


    I'm able to create a .avi file but when I attempt to play it in VLC, the file is 0 seconds long. I'm not sure why. I've looked at tutorials on Youtube but I haven't had any success identifying what I'm doing wrong. I've also asked Claude but it hasn't been able to solve the problem either. Does anyone know what the problem might be or have an alternative approach they would suggest using?

    Continue reading...

Compartilhe esta Página