Article

Converting Audio Files into Mp3 Using FFMPEG, Pydub and Python

Last updated Sept. 11, 2022

...

Converting Audio Files into .mp3 using FFMPEG and Pydub

Having audio files in a single or rather consistent format is essential when playing on different media players. Mp3 format is the most adapted audio codec format and most media players have the capability to render such files. In this tutorial, we will focus on converting other audio formats into mp3.

You will need to have the following installed on your machine. PythonFFmpeg. FFmpeg can be used directly from the terminal if you're looking to convert just a few files. However, if you are converting multiple files, this is where the scripting part with python comes in handy.

After installing the above requirements, add them to the environment path in your machine so you can access the globally. You will also need to install a python package called pydub using the python package manager pip via the following command:

pip install pydub

Then navigate to the folder containing the audio files you wish to manipulate and create a file with a .py extension and paste the following code in:

import os
import pydub
import glob

#you can select the file type you have and comment out the rest.
mkv_files = glob.glob('./*.mkv')
webm_files = glob.glob('./*.webm')
wav_files = glob.glob('./*.wav')
m4a_files = glob.glob('./*.m4a')
flac_files = glob.glob('./*.flac')
mp4_files = glob.glob('./*.mp4')

all_files = [mkv_files,webm_files,wav_files,m4a_files,flac_files,mp4_files]

for files in all_files:
    for file in files:
        mp3_file = os.path.splitext(file)[0] + '.mp3'
        sound = pydub.AudioSegment.from_file(file)
        print("Converting: ",file)
        sound.export(mp3_file, format="mp3")
        os.remove(file)
        print("Conversion Complete")

You can add any other file type you have that's not listed there and it will work like a charm. You can also comment out the rest of the files that you don't have. You can basically customize the file above and make it yours.

You can view the instructions below:

 

Post a Comment

To leave a comment, click the button below to sign in with Google.

Signup To My Newsletter

By subscribing, you will get one email every month on tips, tutorials, and resources to improve your skills as a developer. You will get early access to my courses and videos and also access to special bonus of the time. No spam, unsubscribe at any time





Subscribe
Contact
Contact form