Search code examples
pythonglobpydub

How to merge multiple mp3 files with silence on between?


When I try to merge multiple .mp3 files from a folder using pydub and glob to iterate over the files I get the following error.

from pydub import AudioSegment
from os import getcwd
import glob

cwd = (getcwd()).replace(chr(92), '/')
export_path = f'{cwd}/result.mp3'

MP3_FILES = glob.glob(pathname=f'{cwd}/*.mp3', recursive=True)
silence = AudioSegment.silent(duration=15000)
count, lenght = 0, len(MP3_FILES)

for n, mp3_file in enumerate(MP3_FILES):
    mp3_file = mp3_file.replace(chr(92), '/')
    count += 1
    if count == 1:
        print(n, mp3_file)
        audio1 = AudioSegment.from_mp3(mp3_file)
    elif count == 2:
        audio2 = AudioSegment.from_mp3(mp3_file)
    elif count == 3:
        res = audio1 + silence + audio2
        print('Merging')
        count = 0
    if n+1 == lenght:
        res.export(export_path, format='mp3')
        print('\ndone!')

EXPECTED OUTPUT: one audio file with silence between the orinal audios.

AUDIO_RESULT: audio1 silence audio2 silence audio3...

Traceback:

[mp3 @ 0000021b440ec740] Failed to read frame size: Could not seek to 1026.
C:\Users\Acer\Documents\1 file.mp3: Invalid argument

Solution

  • It says - Invalid argument which might be caused by space used in file path.

    If you pass your file/folder path using command line, the path string should be passed inside a quotation("")

    "C:\Users\Acer\Documents\Upwork\Shashank Rai\mp3 segmented delay\1 speech.mp3"
    

    However, in Windows OS sometimes C:\ creates problem because one single \ is used for special character. Would you please test with double \\ ?

    "C:\\Users\\Acer\\..."

    EDIT 1: would you please test this -

    from pathlib import Path 
    
    cwd = Path.cwd()
    MP3_FILES = list(cwd.rglob('*.mp3'))
    ...
    ...