pythonpython-3.xpydubaudiosegment

Creating an empty AudioSegment File in Python (pydub)


Beginner here. I'm trying to loop through a list of paths to mp3 files and merge all the mp3s:

combined_sounds = AudioSegment.from_mp3('./00.mp3')

for file in files:
  sound = AudioSegment.from_mp3(file)
  combined_sounds= combined_sounds + sound;

# ....

I need to define combined_sounds before going through the list - but I'd like to not put anything into it before going through the loop. Right now my little hack is to use an empty mp3 file 00.mp3, but this isn't the nicest solution. How would I accomplish this?

I tried combined_sounds = '' and combined_sounds = None but both get me errors when I then enter the loop and try to turn it into an AudioSegment. Can I create an empty AudioSegment before the loop maybe?


Solution

  • You can use the empty() function in AudioSegment to create a blank segment:

    combined_sounds = AudioSegment.empty()
    
    for file in files:
       sound = AudioSegment.from_mp3(file)
       combined_sounds += sound