0

I have code in Python that loops through and merges a series of audio files to play a customized sound as follows:

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

How can I export the final sound that is played on my computer through this Python code?

I know it's possible to do something like:

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

But how can I save the custom sound that's outputted through my loops?

Ricardo Francois
  • 752
  • 7
  • 24

2 Answers2

1

You can use a combination of AudioSegment.silent(), AudioSegment.empty() and 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")
Marcelo Paco
  • 2,732
  • 4
  • 9
  • 26
0

To do that you can for example concatenate the audio files you are producing and then export such audio. For example, you can modify your script as:

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")
  • Thanks for the idea! Don't think this is completely right though because I want to also include the `time.sleep(delays)` in the track as well – Ricardo Francois Mar 08 '23 at 02:46