PyDub : Can't Save file in a different directory properly

1.5k Views Asked by At

I have been using this code to convert 10 .wav files in .mp3

song_dir = 'Desktop/Song_test/*wav'
song = glob(song_dir) 
print(song)
for song in song:
    mp3_song = os.path.splitext(song)[0] + '.mp3' 
    sound = pydub.AudioSegment.from_mp3(song)
    sound.export('Desktop/Song_test/Converted/', mp3_song, '.mp3', format="mp3")
print("Conversion Done")

What I want to actually achieve is to pick the .wav file from Song_Test convert it in .mp3 file and save it in a subdirectory within Song_Test named Converter. The new file should have the same name (for this I was trying to use os.path.splitext when I was not trying to save the output in a different directory, this was working fine and the converted files had the same name as the earlier file.

Upon saving it in a new directory, When I run this code error pops up, TypeError: export() got multiple values for argument 'format'. Please guide me how I can do this.

2

There are 2 best solutions below

0
MA Bisk On BEST ANSWER

Try writing the export like this -

sound.export('Desktop/Song_test/Converted/' + mp3_song, format="mp3")
  1. Using the '+' adds 'mp3_song' to the location/name string.
  2. Adding '.mp3' seems to be redundant, since it's included in 'mp3_song'.
0
Neoheurist On

The issue for me turned out to be that Pydub doesn't create directories for the files it exports. The solution was to create the directory immediately before the export() call.

Path(directory).mkdir(parents=True, exist_ok=True)
filename = f"{directory}\\{index}.{EXPORT_FILE_TYPE}"
file_object = sound.export(filename, format=EXPORT_FILE_TYPE)
file_object.close()
self.tagger.write_tags(filename)

Interestingly, I found I had to close() the file object created by PyDub before I could do additional processing on the file (which in my case was manipulating the file's metadata tags)