如何通过Python导出合并和循环播放的音频?

vsnjm48y  于 2023-01-10  发布在  Python
关注(0)|答案(2)|浏览(219)

我用Python编写了代码,循环并合并一系列音频文件,以播放定制的声音,如下所示:

from pydub import AudioSegment
from pydub.playback import play

sounds = []
sounds.append(AudioSegment.from_file("Downloads/my_file.mp3"))
for i in range(4):
    sounds.append(sounds[i].overlay(sounds[0], position=delays[i+1]))

for i in range(len(sounds)):
    counter = 0
    while counter <= 2:
        play(sounds[i])
        time.sleep(delays[i])
        counter = counter + 1

如何通过这段Python代码导出在计算机上播放的最终声音?
我知道你可以这样做:

my_custom_sound.export("/path/to/new/my_custom_sound.mp4", format="mp4")

但是如何保存通过循环输出的自定义声音呢?

kg7wmglp

kg7wmglp1#

可以使用AudioSegment.silent()AudioSegment.empty()AudioSegment concatenation的组合:

from pydub import AudioSegment
from pydub.playback import play

sounds = []
sounds.append(AudioSegment.from_file("Downloads/my_file.mp3"))
for i in range(4):
    sounds.append(sounds[i].overlay(sounds[0], position=delays[i+1]))

my_custom_sound = AudioSegment.empty()
for i in range(len(sounds)):
    counter = 0
    while counter <= 2:
        delay = AudioSegment.silent(duration=delays[i]*1000) # Multiply by 1000 to get seconds from delays[i]. silent(duration=1000) is 1 second long
        my_custom_sound += sounds[I] + delay
        play(sounds[i])
        time.sleep(delays[i])
        counter = counter + 1

my_custom_sound.export("/path/to/new/my_custom_sound.mp4", format="mp4")
cvxl0en2

cvxl0en22#

为此,您可以连接正在生成的音频文件,然后导出此类音频。例如,您可以将脚本修改为:

from pydub import AudioSegment
from pydub.playback import play

track = None
sounds = []
sounds.append(AudioSegment.from_file("Downloads/my_file.mp3"))
for i in range(4):
    sounds.append(sounds[i].overlay(sounds[0], position=delays[i+1]))

for i in range(len(sounds)):
    counter = 0
    while counter <= 2:
        if track is not None:
            track = track + sounds[I]
        else:
            track = sounds[I]
        play(sounds[i])
        time.sleep(delays[i])
        counter = counter + 1

track.export("/path/to/new/my_custom_sound.mp4", format="mp4")

相关问题