Search code examples
pythonconcatenationpydub

Pydub concatenate mp3 in a directory


I would like to concatenate all .mp3s in one directory with pydub. The files are numbered consecutively file0.mp3, file1.mp3 etc.

this code from the example code:

playlist_songs = [AudioSegment.from_mp3(mp3_file) for mp3_file in glob("*.mp3")] 

gives me all files and now I would like to concatenate, like in pseudocode:

for i in playlist_songs:
    append i to finalfile

Is there a way to achieve this or am I approaching it wrong ?

Thanks for the help !


Solution

  • you can start with an empty sound like so:

    combined = AudioSegment.empty()
    for song in playlist_songs:
        combined += song
    
    combined.export("/path/to/output.mp3", format="mp3")
    

    or if you'd like to get a little fancy and use 5 second crossfades you'll have to pop the first song off the list

    combined = playlist_songs[0]
    
    for song in playlist_songs[1:]:
        combined = combined.append(song, crossfade=5000)
    
    combined.export("/path/to/output.mp3", format="mp3")