DEV Community

Free Python Code
Free Python Code

Posted on

Audio File Format Converter using PyDub In Python

from pydub import AudioSegment

# convert any type of audio like mp3, wav, ogg
def convert_audio_file(src_file, from_type, to_type):
    dist_file = src_file.replace(from_type, to_type)
    funcs = {
        'mp3': AudioSegment.from_mp3,
        'wav': AudioSegment.from_wav,
        'ogg': AudioSegment.from_ogg,
    }

    audio = funcs[from_type](src_file)
    audio.export(dist_file, format = to_type)


convert_audio_file('test.ogg', 'ogg', 'mp3')
Enter fullscreen mode Exit fullscreen mode

Explanation:

This Python script utilizes PyDub, a library for audio manipulation, to convert audio files from one format to another. Below is a breakdown of the code:

1. from pydub import AudioSegment: This imports the AudioSegment class from the PyDub library, which is used for audio manipulation tasks.

2. convert_audio_file(src_file, from_type, to_type): This is a function definition named convert_audio_file that takes three parameters:

  • src_file: The source audio file path.
  • from_type: The original format of the audio file.
  • to_type: The desired format to which the audio file will be converted.

3. dist_file = src_file.replace(from_type, to_type): This line generates the path for the converted audio file by replacing the extension of the source file (from_type) with the desired extension (to_type).

4. `funcs = { 'mp3': AudioSegment.from_mp3, 'wav': AudioSegment.from_wav, 'ogg': AudioSegment.from_ogg }: This dictionary funcs maps file types to their corresponding PyDub methods for reading those file types. For example, 'mp3' maps to AudioSegment.from_mp3, 'wav' maps to AudioSegment.from_wav, and 'ogg' maps to AudioSegment.from_ogg`.

5. audio = funcs[from_type](src_file): This line reads the source audio file using the appropriate PyDub method based on the from_type parameter and stores the audio data in the audio variable.

**6. audio.export(dist_file, format=to_type): **This line exports the audio data stored in the audio variable to the specified dist_file path in the desired format specified by to_type.

7. Finally, the script calls the convert_audio_file function with an example conversion: convert_audio_file('test.ogg', 'ogg', 'mp3'). This converts the 'test.ogg' file from OGG format to MP3 format.

In summary, the script provides a convenient way to convert audio files between different formats using PyDub library functions.

Top comments (0)