Concating a list of objects in Python for Pydub module

本小妞迷上赌 提交于 2020-07-19 02:52:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!