I have this python script that is supposed to record my screen, on mac os.
import cv2
import numpy as np
from PIL import ImageGrab
import subprocess
import time
def record_screen():
# Define the screen resolution
screen_width, screen_height = 1440, 900 # Adjust this to match your screen resolution
fps = 30 # Target FPS for recording
# Define the ffmpeg command
ffmpeg_cmd = [
'ffmpeg',
'-y', # Overwrite output file if it exists
'-f', 'rawvideo',
'-vcodec', 'rawvideo',
'-pix_fmt', 'bgr24',
'-s', f'{screen_width}x{screen_height}', # Size of one frame
'-r', str(fps), # Input frames per second
'-i', '-', # Input from pipe
'-an', # No audio
'-vcodec', 'libx264',
'-pix_fmt', 'yuv420p',
'-crf', '18', # Higher quality
'-preset', 'medium', # Encoding speed
'screen_recording.mp4'
]
# Start the ffmpeg process
ffmpeg_process = subprocess.Popen(ffmpeg_cmd, stdin=subprocess.PIPE)
frame_count = 0
start_time = time.time()
while True:
# Capture the screen
img = ImageGrab.grab()
img_np = np.array(img)
# Convert and resize the frame
frame = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
resized_frame = cv2.resize(frame, (screen_width, screen_height))
# Write the frame to ffmpeg
ffmpeg_process.stdin.write(resized_frame.tobytes())
# Display the frame
cv2.imshow('Screen Recording', resized_frame)
# Stop recording when 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Close the ffmpeg process
ffmpeg_process.stdin.close()
ffmpeg_process.wait()
# Release everything when job is finished
cv2.destroyAllWindows()
if __name__ == "__main__":
record_screen()
As you can see, it should be 30 frames per second, but the problem is that when I open the file afterwards its all sped up. I think it has to do with the frame capture rate as oppose to the encoded rate. I’m not quite sure though. If I try to speed the video down afterwards so that it plays in real time the video is just really choppy. And the higher I make the fps, the faster the video plays, meaning the more I have to slow it down and then its still choppy. I’m pretty sure that it captures frames at a really slow rate and then puts them in a video and plays it back at 30fps. Can anyone fix this? Anything that gets a working screen recorder on mac os I will take.
John Thesaurus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.