Site icon FSIBLOG

Build a Screen Recorder Using Python

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

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"

Initialize Video Writer

out = cv2.VideoWriter(output_file, fourcc, fps, (screen_size.width, screen_size.height))

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

Release the Video Writer

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

Enhancing the Functionality

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

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

Countdown Before Recording

Elapsed Time Display

Automatic Filename Generation

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.

Exit mobile version