在 Python 中为 Pydub 模块连接对象列表 [英] Concating a list of objects in Python for Pydub module

查看:45
本文介绍了在 Python 中为 Pydub 模块连接对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一系列 wav 文件合并为一个音频文件.到目前为止,这就是我所拥有的.我无法解决如何将这些对象相加的问题,因为它们都是一个对象.

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

推荐答案

sum 函数失败,因为它的 起始值默认为 0,并且不能添加 AudioSegment 和整数.

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

此外,如果您只想组合文件(并且不需要文件名或 AudioSegment 对象的中间列表),则实际上并不需要单独的循环:

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

这篇关于在 Python 中为 Pydub 模块连接对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆