Record the screen with ffmpeg and Python

Almost all the videos that I upload to youtube uses this method that I am going to explain here. This is the fastest way to record your screen. If you don’t do much of reworking on the videos, like me, this could be the right instruments for you if you want somethin raw but immediate. The video output is very light as it does not occupy much memory.

Install ffmpeg

FFmpeg is the leading multimedia framework to decode, encode, transcode, mux, demux, stream, filter and play. All builds require at least Windows 7 or Mac OS X 10.10.

First of all you need to install ffmpeg: its a great free tool with a tons of features. Go here to see how: click on this link to see how to install ffmpeg

Here is the version for windows

How to avoid recording over the previous recordings

If you want to record the screen you could simply use the ffmpeg command, but if you want to make something a little more sofisticated you can combine the use of ffmpeg with python to get incredible results. Today we want to make a simple script that allows you to record the screen with your voice from the mic avoding to overwrite what you eventually recorded in a previous time.

Other advantages

You can take advantage of this script to record your videos in more step and then join the videos together with join mp4 together. You can even trim some parts of the video that you don’t like. Take a look at this post here to see how you can do it with ffmpeg.

Avoiding overwriting, we said

As I said before this code start looking to a file called output0.mp4 if there is not a file like that in the folder it saves the video with that name, otherwise it will save it with the first free numer that he will find, because it will recall the record function until it finds a name with a number that is not already used by another file in the folder. This is a good feature that allows to avoid overwriting a previous recording and allows also to record in more step so that you can join the files together at the end (go here to get the code to do it).

What do I need to record the screen and my voice on the mic

To record the screen recording also your voice, like I do in the video below, you can use this script made with Python that uses ffmpeg to do the job.

The size of the screen

You need to put the size of the screen that you are using. In my case it was -video_size 1366×768.

The frame rate

Experiment also with the frame rate to see what is the right one. To me it worked the -r 10 frame rate.

The audio

Another thing you will have to change is the audio, because your system could have (probably)a different name for its audio device. Mine was: -i audio=”Microfono (8- Logitech USB Headset)”. You see that is even in italian, because my system is set in this language.

How to get the name of my audio devices?

If you want to see what are the names of your devices you can use this script.

ffmpeg -list_devices true -f dshow -i dummy

pause

Copy this code in an editor and save it as list_of_devices.bat. Then run the file with a double click and you will see something like this:

You can see where I took the name “Microfono (8- Logitech USB Headset). Just copy exactly what you see in your computer and substitute it in your script.

The python script to record the screen

There we are, this is the script. Do the change that you gotta do and … start recording.

import os
import glob

x = 0
def record():
	global x
	if not "H:\\ffmpeg\\output" + str(x) + ".mp4" in glob.glob("H:\\ffmpeg\\*.mp4"):
		filename = "H:\\ffmpeg\\output" + str(x) + ".mp4"
	else:
		x += 1
		record()


	os.system(f"""ffmpeg -y -rtbufsize 200M -f gdigrab -thread_queue_size 1024 -probesize 10M -r 10 -draw_mouse 1 -video_size 1366x768 -i desktop -f dshow -channel_layout stereo -thread_queue_size 1024 -i audio="Microfono (8- Logitech USB Headset)" -c:v libx264 -r 10 -preset ultrafast -tune zerolatency -crf 25 -pix_fmt yuv420p -c:a aac -strict -2 -ac 2 -b:a 128k -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" "{filename}" """)

record()

The second script to record the screen

I want to make a little update to the code. This is the one that I am actually using. I suggest you to put this in the main folder from where the OS starts, so that you can just press the windows button + R and then write rec.py to make it start. This is what I do to record the videos and this is the code:

import os
import glob

x = 0
def record():
	global x
	fld = "H:\\ffmpeg\\output\\output"
	if not fld + str(x) + ".mp4" in glob.glob(fld + "*.mp4"):
		filename = fld + str(x) + ".mp4"
	else:
		x += 1
		record()

	audio = "Microfono (8- Logitech USB Headset)"
	video_size = "1366x768"

	os.system(f"""ffmpeg -y -rtbufsize 200M -f gdigrab -thread_queue_size 1024 -probesize 10M -r 10 -draw_mouse 1 -video_size {video_size} -i desktop -f dshow -channel_layout stereo -thread_queue_size 1024 -i audio="{audio}" -c:v libx264 -r 10 -preset ultrafast -tune zerolatency -crf 25 -pix_fmt yuv420p -c:a aac -strict -2 -ac 2 -b:a 128k -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" "{filename}" """)


record()

It is not very different from the other, but it is easier to change the name of the devices or the size of the screen.

Video explaining the code to record the screen

Record just a window with a name

If you want you can record only one window and not the entire screen with this code

ffmpeg -rtbufsize 1500M -f dshow -i audio="Microfono (8- Logitech USB Headset)" -f gdigrab -framerate 30 -draw_mouse 1 -i title=Trace -pix_fmt yuv420p -profile:v baseline -y Huangbaohua.mp4

pause

Save this file as a .bat file. Remember to make the change to the devices like we’ve seen above for the recording of the entire screen. The name of the window must be exact.

How to compress audio for better quality

I made this code to improve quality of the audio recording during streaming recording or the computer screen and audio, it is a bit longer and asks you in which folder you want to record it and what name you want to give to it:

import os
import glob

x = 0

def ask():
    fld = "H:\\ffmpeg\\output\\"
    new_fld = input("Nuova cartella (opzionale, invio=stessa cartella)?: ")
    # aggiunge la cartella al percorso
    if new_fld != "":
        fld = fld + new_fld + "\\"
        # crea la cartella, se non c'è già
        if new_fld not in os.listdir("H:\\ffmpeg\\output\\"):
            os.mkdir(fld)
    filename = input("Nome del file: ")
    filename = fld + filename + ".mp4"
    return filename

def automatic_name():
    "Crea il nome da solo / ora chiedo il nome del file prima"
    global x

    fld = "H:\\ffmpeg\\output\\output"
    if not fld + str(x) + ".mp4" in glob.glob(fld + "*.mp4"):
        filename = fld + str(x) + ".mp4"
    else:
        x += 1
        record()
    filename = fld + filename + ".mp4"
    return filename


def record(filename):
    # Microfono (HUAWEI USB-C HEADSET)
    audio = "Microfono (8- Logitech USB Headset)"
    # audio = "Microfono (HUAWEI USB-C HEADSET)"
    video_size = "1366x768"
    # added a compressor 15/03/2020
    compressor = "-af acompressor=threshold=0.089:ratio=9:attack=200:release=1000"

    os.system(f"""ffmpeg -y -rtbufsize 200M -f gdigrab -thread_queue_size 1024 -probesize 10M -r 10 -draw_mouse 1 -video_size {video_size} -i desktop -f dshow -channel_layout stereo -thread_queue_size 1024 -i audio="{audio}" {compressor} -c:v libx264 -r 10 -preset ultrafast -tune zerolatency -crf 25 -pix_fmt yuv420p -c:a aac -strict -2 -ac 2 -b:a 128k -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" "{filename}" """)


# filename = "rtmp://youtube_stream_url/03r8-71q2-yrvm-bbe7"
filename = ask()
record(filename)

Change your pc features for audio mic and screen, using this script to check for your devices (create a .bat file with this commands and run it):

ffmpeg -list_devices true -f dshow -i dummy

pause


Subscribe to the newsletter for updates
Tkinter templates
My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts