Python Object List Consolidation for Pydub Module

I am trying to combine a list of wav files together into one audio file. So far, this is what I have. I can't wrap my head around how to sum the objects though, since each one is an object.

import glob, os
from pydub import AudioSegment

wavfiles = []
for file in glob.glob('*.WAV'):
    wavfiles.append(file)

outfile = "sounds.wav"

pydubobjects = []

for file in wavfiles:
    pydubobjects.append(AudioSegment.from_wav(file))


combined_sounds = sum(pydubobjects) #this is what doesn't work of course

# it should be like so
# combined_sounds = sound1 + sound2 + sound 3
# with each soundX being a pydub object

combined_sounds.export(outfile, format='wav')

      

+3


source to share


1 answer


The function sum

fails because its default value is 0 and you cannot add AudioSegment

an integer either .

You just need to add the initial value like so:

combined_sounds = sum(pydubobjects, AudioSegment.empty())

      



Also, you don't need separate loops if you just want to concatenate files (and don't need intermediate lists of filenames or objects AudioSegment

):

import glob
from pydub import AudioSegment

combined_sound = AudioSegment.empty()
for filename in glob.glob('*.wav'):
    combined_sound += AudioSegment.from_wav(filename)

outfile = "sounds.wav"
combined_sound.export(outfile, format='wav')

      

+2


source







All Articles