Smart Screen Recorder with Auto-Pause

import cv2

import numpy as np

import mss

import time

from datetime import datetime


# -----------------------------

# CONFIGURATION

# -----------------------------

FPS = 10

MOTION_THRESHOLD = 50000   # Higher = less sensitive

NO_MOTION_TIME = 2         # seconds to auto pause


# -----------------------------

# Setup screen capture

# -----------------------------

sct = mss.mss()

monitor = sct.monitors[1]   # Primary screen


width = monitor["width"]

height = monitor["height"]


fourcc = cv2.VideoWriter_fourcc(*"XVID")

output_file = f"screen_record_{datetime.now().strftime('%Y%m%d_%H%M%S')}.avi"

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


print("🎥 Screen recording started...")

print("🟢 Recording will pause automatically when screen is idle.")

print("🔴 Press 'Q' to stop recording.\n")


prev_frame = None

last_motion_time = time.time()

recording = True


# -----------------------------

# Recording Loop

# -----------------------------

while True:

    img = np.array(sct.grab(monitor))

    frame = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    gray = cv2.GaussianBlur(gray, (21, 21), 0)


    if prev_frame is None:

        prev_frame = gray

        continue


    # Frame difference

    frame_diff = cv2.absdiff(prev_frame, gray)

    thresh = cv2.threshold(frame_diff, 25, 255, cv2.THRESH_BINARY)[1]

    motion_score = np.sum(thresh)


    if motion_score > MOTION_THRESHOLD:

        last_motion_time = time.time()

        recording = True

    else:

        if time.time() - last_motion_time > NO_MOTION_TIME:

            recording = False


    # Write frame only if motion exists

    if recording:

        out.write(frame)

        status_text = "RECORDING"

        color = (0, 255, 0)

    else:

        status_text = "PAUSED (No Motion)"

        color = (0, 0, 255)


    # Overlay status

    cv2.putText(

        frame,

        status_text,

        (20, 40),

        cv2.FONT_HERSHEY_SIMPLEX,

        1,

        color,

        2

    )


    cv2.imshow("Smart Screen Recorder", frame)

    prev_frame = gray


    if cv2.waitKey(1) & 0xFF == ord("q"):

        break


# -----------------------------

# Cleanup

# -----------------------------

out.release()

cv2.destroyAllWindows()


print(f"\n✅ Recording saved as: {output_file}")


No comments: