1

I want to convert multiple MP3 audio files in a folder to WAV format (with mono type) using python code.

I tried the below code using pydub:

import os
from pydub import AudioSegment

audio_files = os.listdir('path')
# Folder is having audio files of both MP3 and WAV formats
len_audio=len(audio_files)
for i in range (len_audio):
    if os.path.splitext(audio_files[i])[1] == ".mp3":
       mp3_sound = AudioSegment.from_mp3(audio_files[i])
       mp3_sound.export("<path>\\converted.wav", format="wav")

I am getting how will i export the converted wav file with different file names.

please suggest

Life is complex
  • 15,374
  • 5
  • 29
  • 58

2 Answers2

4

I would do something like:

import os
from pydub import AudioSegment

path = "the path to the audio files"

#Change working directory
os.chdir(path)

audio_files = os.listdir()

# You dont need the number of files in the folder, just iterate over them directly using:
for file in audio_files:
    #spliting the file into the name and the extension
    name, ext = os.path.splitext(file)
    if ext == ".mp3":
       mp3_sound = AudioSegment.from_mp3(file)
       #rename them using the old name + ".wav"
       mp3_sound.export("{0}.wav".format(name), format="wav")

You can find more about the format mini language here.

Lyux
  • 453
  • 1
  • 10
  • 22
  • Happy to help, and welcome to Stack Overflow. If this answer or any other one solved your issue, please mark it as accepted :) – Lyux May 10 '19 at 20:36
-2

This is simply just changing the extension name of multiple files

import os
from pathlib import Path
path = "the path to the audio files"
#Change working directory
os.chdir(path)
audio_files = os.listdir()
for file in audio_files:
    p = Path(file)
    p.rename(p.with_suffix('.wav'))
  • tried changing the .mp3 extension to .wav , this does not retains the file signature though , but fulfils my purpose, all the files in the path mentioned are converted to wav in monotype. – Aakash Chauhan Apr 28 '22 at 06:13
  • 1
    This is incorrect, this doesn't actually convert the files from an MP3 format to a Waveform format, it only changes the extension of the file without performing a format conversion. It might still work in an audio player, but it's still functionally an MP3 format file, and any program that uses extensions to try and figure out the format would most likely break. The other answer posted correctly performs the conversion and rename to the expected extension. – Hoppeduppeanut May 03 '22 at 23:44