'Convert multiple MP3 files to WAV in python
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
Solution 1:[1]
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.
Solution 2:[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'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lyux |
Solution 2 | Aakash Chauhan |