为 Pydub 模块连接 Python 中的对象列表

Concating a list of objects in Python for Pydub module

我正在尝试将一系列 wav 文件合并为一个音频文件。到目前为止,这就是我所拥有的。 我不知道如何将对象加在一起,因为它们每个都是一个对象。

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

sum 函数失败,因为它的 starting value defaults to 0,并且您不能添加 AudioSegment 和整数。

您只需像这样添加一个起始值:

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

此外,如果您只想合并文件(并且不需要中间文件名列表或 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')