Create a Screen Recorder Using Python

Python Programming Examples


Creating a screen recorder in Python is simple and efficient using just a few libraries. This tool can capture real-time screen activity and save it as a video file. It's ideal for building tutorials, recording gameplay, or monitoring software usage. Python offers easy access to screen recording functionality with libraries like PyAutoGUI for taking screenshots and OpenCV for handling video output.



What Is a Screen Recorder in Python?

A screen recorder captures the display screen frame by frame and saves it as a video file, such as .avi or .mp4. Python simplifies this task by providing libraries that handle image capture and video encoding.

Purpose:

  • Record the entire screen or a region
  • Save it in a standard video format
  • Automate screen monitoring or tutorial creation

Key Libraries:

  • PyAutoGUI: Captures the screen.
  • OpenCV (cv2): Writes the captured frames into a video file.
  • NumPy: Converts image data to arrays (used internally with OpenCV).

How to Implement a Screen Recorder in Python

Step 1: Install Required Libraries

Use pip to install the required packages:

pip install pyautogui opencv-python

Step 2: Import Libraries

Import the required modules for screen capture and video writing.

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

Step 3: Set Up the Video Writer

Automatically fetch screen size and prepare the output file with a timestamp:

# Get screen resolution
resolution = pyautogui.size()

# Choose video encoding format and create VideoWriter
video_format = cv2.VideoWriter_fourcc(*'XVID')
filename = f"record_output_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.avi"
recorder = cv2.VideoWriter(filename, video_format, 15.0, resolution)

Step 4: Capture and Save Screen Frames

Start with a dynamic countdown and begin recording:

# Dynamic countdown before start
for i in range(3, 0, -1):
    print(f"Starting in {i}...", end="\r")
    time.sleep(1)
print("Recording started!        ")

# Set how long to record (in seconds)
record_seconds = 10
begin_time = time.time()

# Loop for capturing screen frames
while True:
    snapshot = pyautogui.screenshot()
    frame_array = np.array(snapshot)
    frame_bgr = cv2.cvtColor(frame_array, cv2.COLOR_RGB2BGR)
    recorder.write(frame_bgr)
    if (time.time() - begin_time) > record_seconds:
        break

Step 5: Release Resources

Once recording is complete, release all used resources:

recorder.release()
cv2.destroyAllWindows()
print(f"Recording finished. Video saved as '{filename}'")

Complete Example

Use the code below to record your screen for 10 seconds and save it as a video file. The output filename includes a timestamp to avoid overwriting. Adjust the duration or frame rate as needed.

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

# Get screen resolution
resolution = pyautogui.size()

# Choose video encoding format and create VideoWriter
video_format = cv2.VideoWriter_fourcc(*'XVID')
filename = f"record_output_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.avi"
recorder = cv2.VideoWriter(filename, video_format, 15.0, resolution)

# Dynamic countdown before start
for i in range(3, 0, -1):
    print(f"Starting in {i}...", end="\r")  # Overwrite the same line
    time.sleep(1)
print("Recording started!        ")  # Clear the line and confirm start

# Set how long to record (in seconds)
record_seconds = 10
begin_time = time.time()

# Loop for capturing screen frames
while True:
    snapshot = pyautogui.screenshot()
    frame_array = np.array(snapshot)
    frame_bgr = cv2.cvtColor(frame_array, cv2.COLOR_RGB2BGR)
    recorder.write(frame_bgr)
    if (time.time() - begin_time) > record_seconds:
        break

recorder.release()
cv2.destroyAllWindows()
print(f"Recording finished. Video saved as '{filename}'")

Conclusion

You've learned how to build a screen recorder using Python with pyautogui and opencv-python. This script captures your screen in real-time and saves it as a video. You can enhance the code further by adding features like audio, custom capture regions, or GUI controls. Understanding this process allows you the flexibility to create your own recording tools using Python.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram