Top 10 Scripts 2022: Python Screen Recorder

How to Record Your Computer Screen using Python

Screen recordings are a great way to record your computer or pc screen. Not only can you view these recordings later, you can also share them across the web or store them on your local computer.As an everyday person, you possibly want to record what’s going on on your computer. But you might want to also record specific windows that you want to focus on, not just your whole screen.Recording the computer or pc screen to be an impossible task but it’s not. With the help of the python screen recorder you can record the computer or pc screen. You can also record specific window.Recording your screen is a useful way to capture what’s happening on your screen, so you can store it and use it later. If you’re someone who has a hard time remembering what you did, or what you need to do next, having a record of your screen action is a great way to help you out. For example, if you’re trying to fix a bug, you can use the record to remember how to fix the problem, and then maybe re-run the script and fix the bug.

This can be a useful tool if you want to record your screen and share it with others.screen recorder is a software that captures a portion of your desktop or display and records it, either as a video file or a series of images, in real time.Screen recording software is a surefire way to demonstrate computer activity on the screen. With Python screen recorder, you can record whatever is on your screen. This blog will look at the arguments for screen recording and then the steps involved in recording a screen.

Record your windows computer or pc screen using this program. It’s easy to use and to give you a full recording you can use a few features. It’s a screen recorder, and it’s lightweight. All you need is a pc or laptop and this tool.Could you use a screen recorder? If so, you might find the Python Screen Recorder useful. With just a few easy lines of code, you can record your computer or pc screen. You can then share your screen recording with anyone, anytime. Add a logo, add some text, and publish your video. This blog will explain how you can use the Python Screen Recorder.Screen recording in python is a great way to have a video tutorial of what you are doing or show your friends or family how to do a task. It’s also a good way to record your computer screen in case of an accident or encounter with a technical problem. This blog will look at how to do screen recording using python.Keeping all those notes, spreadsheets, websites, pictures, and more can be hard with the limited space on your computer. This is where a screen recorder comes in handy. Screen Recorders let you capture and save your video from your PC or laptop.

Method #1:

Required Modules:

pip install pyautogui
pip install numpy
pip install opencv-python

 

import pyautogui
import cv2
import numpy as np
import random

resolution = tuple(pyautogui.size())
fps = 12.0
codec = cv2.VideoWriter_fourcc(*"MJPG")
filename = "screen_recording"+str(random.randint(0, 1000))+".avi"

# Creating a VideoWriter object
writer = cv2.VideoWriter(str(filename), codec, fps, resolution)

# Creating an Empty window
cv2.namedWindow("Screen Recorder", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Screen Recorder", 480, 270)

while True:
    img = pyautogui.screenshot()
    # Convert the screenshot to a numpy array
    frame = np.array(img)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) #BGR to RGB

    # Writing it to the output file
    writer.write(frame)
    
    # Displaying the recording screen
    cv2.imshow('Screen Recorder', frame)
    
    # Stop recording when we press 'q'
    if cv2.waitKey(1) == ord('q'):
        print("Recording Stopped")
        break

print("Recordings saved as: "+filename)
writer.release()
cv2.destroyAllWindows()

 

Method #2:

Required Modules:

pip install numpy
pip install opencv-python

 

import datetime

from PIL import ImageGrab
import numpy as np
import cv2
from win32api import GetSystemMetrics

width = GetSystemMetrics(0)
height = GetSystemMetrics(1)
time_stamp = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')
file_name = f'{time_stamp}.mp4'
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
captured_video = cv2.VideoWriter(file_name, fourcc, 20.0, (width, height))

webcam = cv2.VideoCapture(1)

while True:
    img = ImageGrab.grab(bbox=(0, 0, width, height))
    img_np = np.array(img)
    img_final = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
    _, frame = webcam.read()
    fr_height, fr_width, _ = frame.shape
    img_final[0:fr_height, 0: fr_width, :] = frame[0: fr_height, 0: fr_width, :]
    cv2.imshow('Secret Capture', img_final)

    # cv2.imshow('webcam', frame)

    captured_video.write(img_final)
    if cv2.waitKey(10) == ord('q'):
        break

 

Method #3:

Required Modules:

pip install pyautogui
pip install numpy
pip install opencv-python

 

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


if not os.path.isfile("Stop Video.txt"):
    with open("Stop Video.txt", 'w') as f:
        f.write('')

def check_if_complete():
  try:
    c = []
    #OPENS FILE FOR READING
    with open("Stop Video.txt", 'r') as f:
            a = f.readlines()

    #TAKES THE CONTENTS OUT OF a AND PUTS THEM IN A ARRAY
    for i in a:
        c.append(i.strip('\n').strip(''))

    #CHECKS IF c CONTAINS THE LAST WORDS OF THE SQL SCAN DAT SHOWS THAT THE SCAN ENDED
    z = 'y'
    if z in c:
        return "FINISHED"
    else:
        return "SCANNING"
  except:
      pass

def stop_recording():
  while True:
    i = input("Enter y to stop recording? ").lower()
    if i == 'y':
        with open("Stop Video.txt", 'a') as f:
                 f.write(i)
        break
    else:
        print("Invalid Entry!!!")

def start_recording():
    count = 0
    screen = (1280, 1024)
    four = cv2.VideoWriter_fourcc(*"XVID")
    output = cv2.VideoWriter(f"output.avi", four, 10.0, (screen))

    fps = 120
    previous = 0
   # try:
    while True:
        if check_if_complete() == 'FINISHED':
            print("Recording Finished")
            with open("Stop Video.txt", 'w') as f:
                f.write('')
            break
        elapsed_time = time.time() - previous

        img = pyautogui.screenshot()

        if elapsed_time > 1.0 / fps:
            previous = time.time()
            frame = np.array(img)
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            output.write(frame)
        cv2.waitKey(100)
        count += 1

    cv2.destroyAllWindows()
    output.release()
    filename = input("Enter file name: ")
    os.rename('output.avi', f'{filename}.avi')
    print(f"Video saved as: {filename}")


if __name__ == '__main__':
    m1 = threading.Thread(target=start_recording)
    m1.start()
    m2 = threading.Thread(target=stop_recording)
    m2.start()

 

Method #4:

Required Modules:

pip install screen-recorder-sdk
pip install colorama

 

import sys
import time
import os
import colorama
from screen_recorder_sdk import screen_recorder 
from colorama import Fore, Back, Style
colorama.init()

def main():
    try:
        if len(sys.argv) == 2 :    
            cwd = os.getcwd()
            print( Fore.GREEN + "Current working directory: {0} ".format(cwd))
            print( Fore.RESET)
            ans = input("Do you want to change the directory:(y/n)?")
            ans = ans.lower()
            if ans == 'y':
                directory = input ("Please specify the path: ")
                isFile = os.path.isfile(directory)
                os.chdir(directory)   
            record_duration = float(input("Enter the record duration in minutes: "))
            file_name = sys.argv[1]
            print(Fore.YELLOW)
            params = screen_recorder.RecorderParams ()
            screen_recorder.init_resources(params)
            screen_recorder.start_video_recording(file_name +'.mp4',30,800000,True)  
            time.sleep(record_duration * 60) 
            screen_recorder.stop_video_recording()
            print(Fore.GREEN)        
            print("Recording stopped. File saved as "+file_name+".mp4")
        elif len(sys.argv) == 1:
            print(Fore.RED + "Oops! please provide a file name")
        else:
            print(Fore.RED + "only one file name at a time is allowed")
    except KeyboardInterrupt:
        print(Fore.RED)
        print("Recording stopped")
        screen_recorder.stop_video_recording()

if __name__ == '__main__':
    main()

 

How to record specific window using Python:

Screen recorders are a great way to record computer screens. The benefit of using a screen recorder is that you can record whatever is on your computer screen, which is especially helpful if you are using your computer for business purposes and you need to record a particular window. However, it is important to note that there are several different types of screen recorders. The most basic one is a program that records the entire screen as it is being displayed. This can be helpful because you can record the entire screen, but it is less helpful if what you want to record is something on the screen that isn’t being displayed, such as a chat window. For that, you would need a screen recorder that has a specific window that you can record. You can also use a screen recorder for your YouTube videos. You can use any screen recorder to record a specific window. You can also use a screen recorder to record your computer’s desktop.

Screen recording is an essential tool for content creators like writers, game developers, and video producers. However, it can also be an essential tool for any developer, especially when debugging their programs. It is easy to use, and it’s a lot easier than writing a program to do what you need. Screen recording is also a great way to record your computer or computer screen. When you are recording a screen, you can record anything that is being displayed on your screen. It can be a website, a game, or a program. Using python, you can record your window and have a lot of flexibility with it. Once you have the recording, you can export it to a file and use it in any program.

The python screen recorder is an application that allows you to easily record your computer or pc screen. It is a simple application that performs a quick and easy task.Record your computer screen using Python!

Method #5:

Required Modules:

pip install pyautogui
pip install numpy
pip install opencv-python

 

import cv2 as cv
import pyautogui
import numpy as np
import keyboard
import time



# Screen size info
left_top_x, left_top_y, left_down_x, left_down_y, right_top_x, right_top_y = 0, 0, 0, 0, 0, 0



def Adjust_screen_size():
    global left_top_x, left_top_y, left_down_x, left_down_y, right_top_x, right_top_y
    pyautogui.alert(text='After moving the mouse to the specified position,pressCtrl,Record video window size (the order is, upper left, lower left, upper right)', title='Set the recording window size', button='OK')
    
    print('Left Top')
    while not keyboard.is_pressed('ctrl'):
        left_top_x, left_top_y = pyautogui.position()
    time.sleep(0.5)
    
    print('Left Down')
    while not keyboard.is_pressed('ctrl'):
        left_down_x, left_down_y = pyautogui.position()
    time.sleep(0.5)

    print('Right Top')
    while not keyboard.is_pressed('ctrl'):
        right_top_x, right_top_y = pyautogui.position()
    time.sleep(0.5)

    screen_x = int(right_top_x) - int(left_top_x)
    screen_y = int(left_down_y) - int(left_top_y)

    return screen_x, screen_y



def Recording(screen_x, screen_y):
    global left_top_x, left_top_y, left_down_x, left_down_y, right_top_x, right_top_y

    print("--- Recording")
    tmp_video = []
    frame_number = 0


    time_start = time.time()
    while True:
        #click screen shot
        screen_shot_img = pyautogui.screenshot()

        #convert into array
        frame = np.array(screen_shot_img)
        #change from BGR to RGB
        frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
        
        tmp_video.append(frame[left_top_y:(left_top_y+screen_y), left_top_x:(left_top_x+screen_x), :])
        frame_number = frame_number + 1     

        if keyboard.is_pressed('ctrl'):
            break
    time_end = time.time()

    print('--- End Recording')
    cv.destroyAllWindows()

    frame_delay = round(frame_number / (time_end - time_start))
    #print(frame_delay)

    return tmp_video, frame_delay



def Replaying(tmp_video, frame_delay):

    print('--- Replaying')
    
    for frame in tmp_video:
        cv.imshow("Replay", frame)
        cv.waitKey(frame_delay)
        if keyboard.is_pressed('ctrl'):
            break
    
    cv.destroyAllWindows()



def Saving(tmp_video, frame_delay, screen_x, screen_y):
    fourcc = cv.VideoWriter_fourcc(*'XVID')
    video = cv.VideoWriter('test.avi', fourcc, 25, (screen_x, screen_y))
    for frame in tmp_video:
        video.write(frame)



if __name__== "__main__":

    screen_x, screen_y = Adjust_screen_size()

    while screen_x < 0 | screen_y < 0:
        print('Setting screen size error')
        screen_x, screen_y = Adjust_screen_size()

    while True:

        buttom_state = pyautogui.confirm(text='Please select a feature', title='Remote live broadcast and commentary of sports events', buttons=['Record', 'Replay', 'Save', 'End'])

        if buttom_state == 'Record':
            tmp_video, frame_delay = Recording(screen_x, screen_y)

        elif buttom_state == 'Replay':
            # check whether you have record yet
            if tmp_video:
                Replaying(tmp_video, frame_delay)
            else:
                buttom_state = pyautogui.confirm(text='After moving the mouse to the specified position', title='Remote live broadcast and commentary of sports events', buttons=['Record', 'Replay', 'Save', 'End'])

        elif buttom_state == 'Save':
            if tmp_video:
                Saving(tmp_video, frame_delay, screen_x, screen_y)
            else:
                buttom_state = pyautogui.confirm(text='Please record first', title='Remote live broadcast and commentary of sports events', buttons=['Record', 'Replay', 'Save', 'End'])

        else:
            break

 

Method #6:

Required Modules:

pip install PyQt5

 

from PyQt5.QtCore import *
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import os
import sys


class VideoWindow(QMainWindow):
    """ From https://pyobfuscate.com/"""
    def __init__(self, parent=None):
        super(VideoWindow, self).__init__(parent)
        self.setWindowTitle("Screenshot Recorder")

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.videoWidget = QVideoWidget()

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.speedupButton = QPushButton()
        self.speedupButton.setEnabled(False)
        self.speedupButton.setIcon(self.style().standardIcon(QStyle.SP_MediaSeekForward))
        self.speedupButton.clicked.connect(self.speed_up)

        self.slowdownButton = QPushButton()
        self.slowdownButton.setEnabled(False)
        self.slowdownButton.setIcon(self.style().standardIcon(QStyle.SP_MediaSeekBackward))
        self.slowdownButton.clicked.connect(self.slow_down)

        self.normspeedButton = QPushButton()
        self.normspeedButton.setEnabled(False)
        self.normspeedButton.setIcon(self.style().standardIcon(QStyle.SP_ArrowUp))
        self.normspeedButton.clicked.connect(self.norm_speed)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.errorLabel = QLabel()
        self.errorLabel.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)

        # Create new action
        openAction = QAction(QIcon('open.png'), '&Open', self)        
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open movie')
        openAction.triggered.connect(self.openFile)

        # Create exit action
        exitAction = QAction(QIcon('exit.png'), '&Exit', self)        
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.exitCall)

        # Create menu bar and add action
        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        #fileMenu.addAction(newAction)
        fileMenu.addAction(openAction)
        fileMenu.addAction(exitAction)

        # Create a widget for window contents
        wid = QWidget(self)
        self.setCentralWidget(wid)

        # Create layouts to place inside widget
        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.slowdownButton)
        controlLayout.addWidget(self.normspeedButton)
        controlLayout.addWidget(self.speedupButton)
        controlLayout.addWidget(self.positionSlider)

        layout = QVBoxLayout()
        layout.setSpacing(0)

        layout.addWidget(self.videoWidget)
        layout.addLayout(controlLayout)

        # Set widget to contain window contents
        wid.setLayout(layout)
        self.grabber = VideoFrameGrabber(self)
        self.mediaPlayer.setVideoOutput([self.videoWidget.videoSurface(), self.grabber])
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)

        self._default_playbackrate = 1
        self._current_playbackrate = None
        self.videoWidget.setMinimumSize(500, 500)

        layout.addWidget(self.errorLabel)
        layout.setAlignment(Qt.AlignBottom)
        self.folder = FolderSelector()
        layout.addWidget(self.folder)

        hint = QLabel()
        hint.setText('Press S to save a screenshot to the folder displayed above.')
        layout.addWidget(hint)

        self.video_name = None
        self.video_path = None
        self.grabber.frameAvailable.connect(self.process_frame)

    def openFile(self):
        fileName, _ = QFileDialog.getOpenFileName(self, "Open Movie", QDir.homePath())

        if fileName != '':
            self.mediaPlayer.stop()
            self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(fileName)))
            self.playButton.setEnabled(True)
            self.speedupButton.setEnabled(True)
            self.slowdownButton.setEnabled(True)
            self.normspeedButton.setEnabled(True)
            self._current_playbackrate = 1
            self.video_name = os.path.splitext(os.path.basename(fileName))[0]
            self.video_path = f'{os.path.dirname(fileName)}/{self.video_name}'
            self.folder.file.setText(self.video_path)

    def keyPressEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key_S:
            self.grabber.save_image()

    def process_frame(self, frame: QImage, timestamp: int):
        is_playing = self.mediaPlayer.state()
        self.mediaPlayer.pause()
        if not os.path.exists(self.folder.get_path()):
            os.mkdir(self.folder.get_path())
        file_name = f'{self.folder.get_path()}/{timestamp}.png'
        frame.save(file_name)
        if is_playing == QMediaPlayer.PlayingState:
            self.mediaPlayer.play()

    def exitCall(self):
        sys.exit(app.exec_())

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def slow_down(self):
        self._current_playbackrate = self._current_playbackrate * 0.5
        self.mediaPlayer.setPlaybackRate(self._current_playbackrate)

    def speed_up(self):
        self._current_playbackrate = self._current_playbackrate * 2
        self.mediaPlayer.setPlaybackRate(self._current_playbackrate)

    def norm_speed(self):
        self.mediaPlayer.setPlaybackRate(self._default_playbackrate)
        self._current_playbackrate = self._default_playbackrate

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(
                    self.style().standardIcon(QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(
                    self.style().standardIcon(QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.errorLabel.setText("Error: " + self.mediaPlayer.errorString())


class VideoFrameGrabber(QAbstractVideoSurface):
    """ From https://stackoverflow.com/questions/55349153/pyqt5-grabbing-current-frame-displays-blank"""
    frameAvailable = pyqtSignal(QImage, int)

    def __init__(self, parent: QObject = None):
        super().__init__(parent)
        self._grab_frame = False

    def supportedPixelFormats(self, handleType):
        return [QVideoFrame.Format_ARGB32, QVideoFrame.Format_ARGB32_Premultiplied,
                QVideoFrame.Format_RGB32, QVideoFrame.Format_RGB24, QVideoFrame.Format_RGB565,
                QVideoFrame.Format_RGB555, QVideoFrame.Format_ARGB8565_Premultiplied,
                QVideoFrame.Format_BGRA32, QVideoFrame.Format_BGRA32_Premultiplied, QVideoFrame.Format_BGR32,
                QVideoFrame.Format_BGR24, QVideoFrame.Format_BGR565, QVideoFrame.Format_BGR555,
                QVideoFrame.Format_BGRA5658_Premultiplied, QVideoFrame.Format_AYUV444,
                QVideoFrame.Format_AYUV444_Premultiplied, QVideoFrame.Format_YUV444,
                QVideoFrame.Format_YUV420P, QVideoFrame.Format_YV12, QVideoFrame.Format_UYVY,
                QVideoFrame.Format_YUYV, QVideoFrame.Format_NV12, QVideoFrame.Format_NV21,
                QVideoFrame.Format_IMC1, QVideoFrame.Format_IMC2, QVideoFrame.Format_IMC3,
                QVideoFrame.Format_IMC4, QVideoFrame.Format_Y8, QVideoFrame.Format_Y16,
                QVideoFrame.Format_Jpeg, QVideoFrame.Format_CameraRaw, QVideoFrame.Format_AdobeDng]

    def present(self, frame: QVideoFrame):
        if frame.isValid():
            frame = QVideoFrame(frame)
            frame.map(QAbstractVideoBuffer.ReadOnly)
            image = QImage(frame.bits(), frame.width(), frame.height(), frame.bytesPerLine(), QVideoFrame.imageFormatFromPixelFormat(frame.pixelFormat()))
            if self._grab_frame:
                self.frameAvailable.emit(image, frame.startTime())  # this is very important
                self._grab_frame = False
        return True

    def save_image(self):
        self._grab_frame = True


class FolderSelector(QWidget):
    """
    Widget with a LineEdit and a button to the right for selecting either a folder or a file
    """
    def __init__(self):
        """
        :param folder: whether or not to ask for a folder or a file
        """
        super(FolderSelector, self).__init__()
        self.setLayout(QHBoxLayout())
        self.file = QLineEdit()
        self.file.setMinimumWidth(500)
        self.file.setPlaceholderText('C:\\\\Path\\to\\where_videos\\will_be_saved\\')
        self.find_btn = QPushButton('Select Folder')
        self.find_btn.clicked.connect(self.select_folder)
        self.layout().addWidget(self.file)
        self.layout().addWidget(self.find_btn)

    def select_folder(self):
        """
        Called when the button is pushed. Fills the LineEdit with the folder/file selected.
        :return:
        """
        file = QFileDialog.getExistingDirectory(self, "Select Directory")
        self.file.setText(file)

    def get_path(self):
        """
        :return: the text in the LineEdit
        """
        return self.file.text()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    player = VideoWindow()
    player.resize(640, 480)
    player.show()
    sys.exit(app.exec_())

 

Python Screen Recorder:

Python screen recording is a process of recording screen activity to a file or a video file. A screen recorder can be used to capture a computer or a PC screen for one or more users, for recording of a specific window, for capturing of live audio/video, or for recording of a specific program. It is not necessary that the user of a screen recorder is the one who is recording the screen activity. In a workplace, a screen recorder is used to record a video of a sales presentation. It is also used to record a video of a class or a meeting.In order to record your computer or pc screen using python, you can use the following command to record your screen for a specific window by using python. To record your screen, use the following command in the terminal: python -m SimpleHTTPServer To record a specific window, use the following command: python -m SimpleHTTPServer -s “http://localhost:8181/index.html

The python screen recorder is a simple, yet powerful tool that allows you to record your computer screen with python. It is easy to use and can be used to record specific windows of your computer. The python screen recorder is useful for many purposes. You can use it to record how to use a website or how to create an app. The python screen recorder is also useful for recording tutorials or making screencasts.

Method #7:

Required Modules:

pip install pyautogui
pip install numpy
pip install opencv-python

 

import cv2
import tkinter as tk
import numpy as np
import pyautogui
from tkinter.filedialog import asksaveasfilename
import time
import sys

def run():
    # display screen resolution, get it from your OS settings
    SCREEN_SIZE = pyautogui.size()
    # define the codec
    fourcc = cv2.VideoWriter_fourcc(*"XVID")
    # create the video write object
    file_name = asksaveasfilename(confirmoverwrite=False,defaultextension='.avi')
    out = cv2.VideoWriter(file_name, fourcc, 20.0, (SCREEN_SIZE))
    print("Recording Started...\n")
    odd=1
    while True:
        odd+=1
        # make a screenshot
        img = pyautogui.screenshot()
        # convert these pixels to a proper numpy array to work with OpenCV
        frame = np.array(img)
        # convert colors from BGR to RGB
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        if(odd==10):
            cv2.imshow("Recording...", frame)
            odd=1
        # if the user clicks q, it exits
        if cv2.waitKey(1) == ord("q"):
            cv2.destroyAllWindows()
            break
        # write the frame
        out.write(frame)
    out.release()
    root.destroy()
    sys.exit(0)

def screenshot():
    root.destroy()
    print("Screen Shot...\n")
    time.sleep(1)
    myScreenshot = pyautogui.screenshot()
    file_name = asksaveasfilename(confirmoverwrite=False,defaultextension='.png')
    myScreenshot.save(file_name)
    sys.exit(0)
    
root = tk.Tk()
root.title("Screen Recorder")
root.geometry("600x220")

root.configure(background = '#e6e5e5')
frame = tk.Frame(root,bg = '#e6e5e5',pady = 1, width =550, height = 50)
frame.grid(row=0,column=0)
frame.pack()  
label0 = tk.Label(frame,font=('Comic Sans MS',26,'bold'),text = "          Screen Recorder          ",bg= '#663300',fg='white',justify ="center")
label0.pack(side=tk.TOP)
button =tk.Button(frame, font=('arial', 20,'bold'), text="Start Recording",padx=2,pady=2, bg="green",fg = "white",command=run)
button.pack(side=tk.TOP)
button1 =tk.Button(frame, font=('arial', 20,'bold'), text="Take Screenshot",padx=2,pady=2, bg="orange",fg = "white",command=screenshot)
button1.pack()
root.mainloop()

 

Method #8:

Required Modules:

pip install mss
pip install numpy
pip install opencv-python

 

import os
import ctypes
import cv2 as cv
import numpy as np
from util import getResolution
from mss import mss

with mss() as sct:
  # Gets Screen Resolution
  user32 = ctypes.windll.user32
  user32.SetProcessDPIAware()
  [width, height] = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
  
  # Define Video Type
  codec = cv.VideoWriter_fourcc(*"mp4v")
  out = cv.VideoWriter("video.mp4", codec, 7, (width, height))

  # Live Video Display
  cv.namedWindow("Live", cv.WINDOW_NORMAL)
  cv.resizeWindow("Live", 480, 270)

  # Gets Desired Monitor
  monitor_number = 1
  monitor_data = sct.monitors[monitor_number]

  # Monitor Data
  monitor = {
    "top": monitor_data["top"],
    "left": monitor_data["left"],
    "width": width,
    "height": height,
  }

  while True:
    # Grabs Frame + Converts to Numpy Array + Converts Color
    frame = np.array(sct.grab(monitor))

    out.write(frame)
    cv.imshow("Live", frame)

    # Exits if Q is pressed
    if cv.waitKey(1) == ord('q'):
      break

# Cleanup
out.release()
cv.destroyAllWindows()

os.rename("video.mp4", "recording.mp4")

 

Method #9:

Required Modules:

pip install pypiwin32
pip install numpy

 

"""
Getting frames:
    https://towardsdatascience.com/lightning-fast-video-reading-in-python-c1438771c4e6
    https://github.com/dmlc/decord
    
Faster video file FPS with cv2.VideoCapture and OpenCV
https://stackoverflow.com/questions/3586046/fastest-way-to-take-a-screenshot-with-python-on-windows Raster: https://docs.microsoft.com/en-us/windows/win32/gdi/raster-operation-codes https://docs.microsoft.com/en-us/windows/win32/gdi/binary-raster-operations https://docs.microsoft.com/en-us/windows/win32/gdi/ternary-raster-operations https://lazarus-ccr.sourceforge.io/docs/lcl/lclintf/bitblt.html Import Docs pywin32api: http://timgolden.me.uk/pywin32-docs/PyWin32.html https://yiyibooks.cn/__src__/meikunyuan6/pywin32/pywin32/PyWin32/win32api.html win32: http://timgolden.me.uk/pywin32-docs/win32.html win32gui: http://timgolden.me.uk/pywin32-docs/win32gui.html https://yiyibooks.cn/__src__/meikunyuan6/pywin32/pywin32/PyWin32/win32gui.html win32ui: http://timgolden.me.uk/pywin32-docs/win32ui.html https://yiyibooks.cn/__src__/meikunyuan6/pywin32/pywin32/PyWin32/win32ui.html win32con: http://timgolden.me.uk/pywin32-docs/win32console.html Other Docs Windows GDI: https://docs.microsoft.com/en-us/windows/win32/api/_gdi/ """ import time import win32api import win32gui, win32ui, win32con import numpy as np class WindowCapture: # Properties handle = None handle_index = None handle_context = None mem_device_context = None data_bit_map = None raster = None original_window_size = 0 x, y, w, h = 0, 0, 0, 0 # Croppable window size properties def __init__(self, window_name=None, region=None, raster=win32con.SRCCOPY): """ Find the desired window and setup resources to copy and send commands to it. :param window_name: The window name :param region: Optional size for a cropped window :param raster: The method used to copy the original frame """ if window_name is None: self.handle = win32gui.GetDesktopWindow() else: self.handle = win32gui.FindWindow(None, window_name) if not self.handle: raise Exception('Window not found: {}'.format(window_name)) # Original size window_size = win32gui.GetWindowRect(self.handle) self.original_window_size = window_size[0], window_size[1], window_size[2] - window_size[0], window_size[3] - window_size[1] # Set cropped size if applicable. if region is None: self.x, self.y, self.w, self.h = window_size[0], window_size[1], window_size[2] - window_size[0], window_size[3] - window_size[1] else: self.x, self.y, self.w, self.h = region[0], region[1], region[2], region[3] # Set handle properties self.handle_index = win32gui.GetWindowDC(self.handle) self.handle_context = win32ui.CreateDCFromHandle(self.handle_index) self.mem_device_context = self.handle_context.CreateCompatibleDC() self.data_bit_map = win32ui.CreateBitmap() self.data_bit_map.CreateCompatibleBitmap(self.handle_context, self.w, self.h) self.raster = raster def win32api_capture_screenshot(self, pad=0): """ Captures a frame of the desired window and converts it to opencv format """ x, y, w, h = self.x, self.y, self.w, self.h self.mem_device_context.SelectObject(self.data_bit_map) self.mem_device_context.BitBlt((pad, pad), (w, h), self.handle_context, (x, y), self.raster) # Converting the bitmap into something opencv can read signed_ints_array = self.data_bit_map.GetBitmapBits(True) img = np.fromstring(signed_ints_array, dtype='uint8') img.shape = (h, w, 4) return img def release_objects(self): """ Releases the objects from memory. Call this when finished capturing the window. """ self.handle_context.DeleteDC() self.mem_device_context.DeleteDC() win32gui.ReleaseDC(self.handle, self.handle_index) win32gui.DeleteObject(self.data_bit_map.GetHandle()) def get_mouse_pos(self): x, y, w, h = self.original_window_size pos = win32gui.GetCursorPos() _x = round(pos[0] / w, 2) _y = round(pos[1] / h, 2) return pos, (_x, _y) def set_mouse_position(self, x, y): w, h = self.original_window_size[2], self.original_window_size[3] win32api.SetCursorPos((int(w*x), int(h*y))) def foreground_send_click(self, x, y, click_type="left"): """ Sends click events to the foreground window """ w, h = self.original_window_size[2], self.original_window_size[3] win32api.mouse_event(win32con.MOUSEEVENTF_MOVE | win32con.MOUSEEVENTF_ABSOLUTE, int(x / w * 65535.0), int(y / h * 65535.0)) if click_type == "left": win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0) elif click_type == "ctrl+left": win32api.keybd_event(win32con.VK_CONTROL, 0, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0) win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0) else: win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN, x, y, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP, x, y, 0, 0) def foreground_scroll(self, scroll_amount, x=0, y=0): """ Sends scroll events to the foreground window """ w, h = self.original_window_size[2], self.original_window_size[3] win32api.mouse_event(win32con.MOUSEEVENTF_MOVE | win32con.MOUSEEVENTF_ABSOLUTE, int(x / w * 65535.0), int(y / h * 65535.0)) direction = 1 if scroll_amount > 0 else -1 ticks = 0 while ticks < abs(scroll_amount): win32api.mouse_event(win32con.MOUSEEVENTF_WHEEL, x, y, direction, 0) ticks += 1 @staticmethod def print_window_names(): """ Prints the names of all the avaliable windows """ def win_enum_handler(handle, ex): if win32gui.IsWindowVisible(handle): print(hex(handle), win32gui.GetWindowText(handle)) win32gui.EnumWindows(win_enum_handler, None) @staticmethod def foreground_send_chars(chars): """ https://devblogs.microsoft.com/oldnewthing/20050530-11/?p=35513 https://stackoverflow.com/questions/31713835/win32apis-keybd-event-function-problems """ string = str(chars) for char in string: win32api.keybd_event(ord(char), 0, 0, 0) time.sleep(.1) win32api.keybd_event(ord(char), 0, win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.2)

 

Method #10:

Required Modules:

pip install moviepy
pip install numpy
pip install PyAudio
pip install opencv-python

 

from tkinter import *
import threading
from pyautogui import screenshot
import numpy as np
import cv2
import pyaudio
import wave
import os
from moviepy.editor import *



# Video

video_recording = True

fourcc = cv2.VideoWriter_fourcc(*'XVID')
videoWriter = None

def start_video_recording():
    global videoWriter
    videoWriter = cv2.VideoWriter('C:\\Users\\Aprameya\\AppData\\Local\\Temp\\video.avi', fourcc, 20, (1366, 768))
    while video_recording:
        img = np.array(screenshot())
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        videoWriter.write(img)
        img = cv2.resize(img, (int(img.shape[1]/1.3), int(img.shape[0]/1.3)))
        cv2.waitKey(1)
    cv2.destroyAllWindows()

def stop_video_recording():
    global video_recording
    video_recording = False
    videoWriter.release()






# Audio

# Constants
chunk = 1024
sample_format = pyaudio.paInt16
channels = 2
fs = 48000

p = None
stream = None
frames = None

audio_recording = True

def start_audio_recording():
    global p, stream, frames
    p = pyaudio.PyAudio()
    stream = p.open(format=sample_format,channels=channels,rate=fs,frames_per_buffer=chunk,input=True)
    frames = []
    while audio_recording:
        data = stream.read(chunk)
        frames.append(data)


def stop_audio_recording():
    global audio_recording, p, stream, frames
    audio_recording = False
    put_into_file()




def put_into_file():
    stream.stop_stream()
    stream.close()
    p.terminate()
    wf = wave.open('C:\\Users\\Aprameya\\AppData\\Local\\Temp\\audio.wav', 'wb')
    wf.setnchannels(channels)
    wf.setsampwidth(p.get_sample_size(sample_format))
    wf.setframerate(fs)
    wf.writeframes(b''.join(frames))
    wf.close()



# Combining audio and video

def combine():
    videoclip = VideoFileClip("C:\\Users\\Aprameya\\AppData\\Local\\Temp\\video.avi")
    audioclip = AudioFileClip("C:\\Users\\Aprameya\\AppData\\Local\\Temp\\audio.wav")
    new_audioclip = CompositeAudioClip([audioclip])
    videoclip.audio = new_audioclip
    videoclip.write_videofile("C:\\Users\\Aprameya\\AppData\\Local\\Temp\\output.mp4")

def ask_to_save_file():
    from tkinter import filedialog
    filepath = filedialog.asksaveasfilename(title='Save Recording', filetypes=(('MP4 File', '*.mp4'),))
    if filepath.endswith('.mp4'):
        pass
    else:
        filepath = filepath + '.mp4'
    file = open(filepath, 'wb')
    outpath = 'C:\\Users\\Aprameya\\AppData\\Local\\Temp\\output.mp4'
    out = open(outpath, 'rb')
    outcont = out.read()
    file.write(outcont)
    file.close()
    out.close()





# Main Program

root = Tk()
root.title('Screen Recorder')
root.geometry('400x250')

def start_recording():
    stop_recording_button['state'] = NORMAL
    threading.Thread(target=start_video_recording).start()
    threading.Thread(target=start_audio_recording).start()
    label.config(text='Recording...')

def stop_recording():
    stop_video_recording()
    stop_audio_recording()
    stop_recording_button['state'] = DISABLED
    label.config(text='Finished Recording!')
    try:
        os.remove('C:\\Users\\Aprameya\\AppData\\Local\\Temp\\output.mp4')
    except:
        pass
    combine()
    ask_to_save_file()
    try:
        os.remove('C:\\Users\\Aprameya\\AppData\\Local\\Temp\\video.avi')
        os.remove('C:\\Users\\Aprameya\\AppData\\Local\\Temp\\audio.wav')
        os.remove('C:\\Users\\Aprameya\\AppData\\Local\\Temp\\output.mp4')
    except:
        pass
    root.destroy()
    exit()

start_recording_button = Button(root, text='Start Recording', font=('Comic Sans Ms', 15), fg='green', borderwidth=5, command=start_recording)
start_recording_button.pack()

stop_recording_button = Button(root, text='Stop Recording', font=('Comic Sans Ms', 15), fg='red', state=DISABLED, borderwidth=5, command=stop_recording)
stop_recording_button.pack()

label = Label(root)
label.pack()

root.mainloop()

 

Conclusion:

This post is a great place to start if you want to record a specific window on your computer.We know that sometimes it can be tricky when you want to record your computer screen but don’t know how to do it. We are here to tell you that it is possible by using python.A way to record your computer or pc screen using Python. Many people find this to be a useful tool as they can record a specific window and save the video to share online. Screen recorders are an effective way to record your computer screen, but they can be hard to use and complicated. Our blog post will highlight some of the more popular screen recorders and show you how they work. Python is a programming language that is a leader in terms of popularity, and is used in many different fields including web development, game development, data analysis, and scientific computing. This python screen recorder can be run on Windows, Mac, or Linux, and is the easiest screen recorder on the market to use. You can record your computer or laptop screen with just a few clicks. There is a built-in option to automatically save the video when you are done recording and to upload the video to youtube. This simple python program will allow you to record your screen and we hope that you find this helpful.