MKV To MP4 Converter with Python

Abdullah Al Rafi
2 min readApr 5, 2021
Killjoy — Valorant
Killjoy — Valorant

Backstory

I have a monitor which has two refresh rates for different resolution. With the full 1920x1080 resolution, it’s 60hz. If I lower it to 1152x864, it’s 75hz. Since I love playing video games and I have been playing Valorant by Riot Games for quite some times, I lowered my resolution to get more refresh rate. Also, low resolution gives me average 120 fps in game. So, I decided to start clipping my gameplay with OBS.

Turns out, if you use the replay buffer to clip, it stores the video in MKV format only. When I tried to edit the clip in Adobe Premiere Pro, I couldn’t open it. One hour later, I created my own converter with Python.

Tutorial

Firstly, there are some dependencies we need to take care of. You need to have following things installed and properly configured such as environment variables on your computer:

Secondly, we will create a new folder project folder with any relevant name. I will name mine as video converter. In the root folder I will create the following things:

  • assets (we will store our .mkv files in this folder)
  • main.py (we will write our code here)

Thirdly, we will import os & subprocess in the first two lines. We will check if the assets folder exists. If it doesn’t we will raise an exception. Next, We will get the list of all the assets AKA .mkv files. Then we will check again if our output folder named result exists or not. If it doesn’t we will create one.

After that, we will do the main part of this script, the conversion. we will take the mkv_list and run it in a for-loop. We will check the extension of each file first to ensure there are MKV formatted files only. If we find anything else, we will raise an exception. Then, we will name our output file name same as the input file but with .mp4 extension. Finally, we will run the FFMPEG command with subprocess , handle any exception to do the conversion and open the designation folder with a printed message once the program has reached to an end.

Final Code

At the end, our main.py will look like this.

Repo Link: https://git.io/JYH8i

Finally

Now that you know how to convert a video file, you will get rid of the monotonous steps of uploading > converting > downloading files. Also, it is blazing fast depending on your hardware.

If you liked my tutorial, let me know in the comments. If you didn’t, do let me know in the comments! Until then, stay safe, stay healthy.

--

--

Abdullah Al Rafi

An enthusiast, simulator freak, love to ride bicycle and say “Hello” to the “World”;