简体   繁体   中英

Concating a list of objects in Python for Pydub module

I'm attempting to join 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 together though since they are each 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')

The sum function is failing because its starting value defaults to 0 , and you can't add an AudioSegment and an integer.

You just need to add a starting value like so:

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

In addition, you don't really need the separate loops if you just want to combine the files (and have no need for the intermediate lists of filenames or AudioSegment objects):

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM