Build a Screen Recorder Using Python

In today’s digital world, screen recording has become an essential tool for tutorials, presentations, and content creation. Fortunately, Python provides an efficient way to build a simple yet powerful screen recorder using readily available libraries. In this blog, I will walk you through the process of creating a screen recorder from scratch, enhancing it with practical functionalities, and discussing future improvements.

Installing Required Libraries

Before we begin, install the necessary libraries by running the following command:

pip install opencv-python pyautogui numpy keyboard

These libraries will help us capture the screen, process video frames, and detect keyboard events.

Understanding the Code

Import Necessary Modules

import cv2
import numpy as np
import pyautogui
import keyboard
  • cv2 (OpenCV): Used for video processing.
  • numpy: Converts screen images into arrays for OpenCV processing.
  • pyautogui: Captures the screen as images.
  • keyboard: Detects key presses to start or stop the recording.

Set Up Screen Recording Parameters

screen_size = pyautogui.size()  # Get screen resolution
fps = 20  # Frames per second
fourcc = cv2.VideoWriter_fourcc(*"XVID")  # Video format
output_file = "screen_recording.mp4"
  • screen_size: Fetches the screen width and height.
  • fps: Sets the frame rate.
  • fourcc: Specifies the video codec.
  • output_file: Defines the name of the recorded video.

Initialize Video Writer

out = cv2.VideoWriter(output_file, fourcc, fps, (screen_size.width, screen_size.height))
  • The cv2.VideoWriter object is used to store the captured frames into a video file.

Start Recording

print("Recording... Press 'q' to stop.")
while True:
    screen = pyautogui.screenshot()  # Capture the screen
    frame = np.array(screen)  # Convert the screenshot to a NumPy array
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)  # Convert RGB to BGR
    out.write(frame)  # Write frame to video file

    if keyboard.is_pressed('q'):
        print("Recording stopped.")
        break
  • A continuous loop captures the screen, converts it into an OpenCV-friendly format, and writes it to the output file.
  • Pressing ‘q’ stops the recording.

Release the Video Writer

out.release()
print(f"Video saved to {output_file}")
  • This ensures the video file is properly saved and closed.

Enhancing the Functionality

The basic script works well, but let’s improve it with practical features:

  • Allow the user to set a recording duration.
  • Add a countdown before recording starts.
  • Display elapsed recording time.
  • Generate unique filenames to avoid overwriting existing recordings.

Enhanced Code with More Features

import cv2
import numpy as np
import pyautogui
import keyboard
import time
from datetime import datetime

screen_size = pyautogui.size()
duration = int(input("Enter recording duration in seconds (or 0 for manual stop): "))

fps = 20
fourcc = cv2.VideoWriter_fourcc(*"XVID")
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
output_file = f"screen_recording_{timestamp}.mp4"
out = cv2.VideoWriter(output_file, fourcc, fps, (screen_size.width, screen_size.height))

print("Recording starts in:")
for i in range(3, 0, -1):
    print(i)
    time.sleep(1)

print("Recording... Press 'q' to stop.")
start_time = time.time()

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

    elapsed_time = int(time.time() - start_time)
    print(f"Recording time: {elapsed_time} sec", end="\r")

    if keyboard.is_pressed('q') or (duration > 0 and elapsed_time >= duration):
        print("\nRecording stopped.")
        break

out.release()
print(f"Video saved to {output_file}")

Key Improvements

User Input for Duration

  • The user can now specify a recording duration.
  • If 0 is entered, the script runs indefinitely until manually stopped.

Countdown Before Recording

  • The script now includes a 3-second countdown before recording starts.

Elapsed Time Display

  • The terminal shows the duration of the recording in real-time.

Automatic Filename Generation

  • The script generates a unique filename for each recording using the current timestamp.

Example Output

Enter recording duration in seconds (or 0 for manual stop): 10
Recording starts in:
3
2
1
Recording... Press 'q' to stop.
Recording time: 5 sec
Recording time: 10 sec
Recording stopped.
Video saved to screen_recording_2025-01-27_14-30-15.mp4

Future Enhancements

While this script is functional, we can take it even further:

  1. Record Audio Along with the Screen
    • Use pyaudio to capture microphone or system audio.
  2. Implement a GUI
    • Create an easy-to-use interface using tkinter or PyQt.
  3. Add Mouse and Keyboard Logging
    • Ideal for creating tutorial videos or training materials.

Final Thoughts

Creating a screen recorder with Python is both a fun and practical project. With just a few lines of code, we can capture high-quality screen recordings, and with further enhancements, we can turn this into a fully-featured recording tool. Whether you’re making tutorials, recording presentations, or capturing gameplay, this script provides a great starting point.

Related blog posts