问题
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')
回答1:
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')
来源:https://stackoverflow.com/questions/30203964/concating-a-list-of-objects-in-python-for-pydub-module