Search code examples
python-3.xaudiowavpydub

Trimming audio returns empty files (Python)


I'm trying to trim multiple .wav files considering different starting points (seconds), however the code I made returns only empty files.

Here is the code considering two files with two different starting points:

from pydub import AudioSegment
import os
path  = "PATH"
files = os.listdir(path)
#start of first song starts at 20 seconds;
#start of second song starts at 15 seconds
startSec = [20,15] 

endSec   = []

for s in startSec:
    endSec.append(s + 30) # adding thirty seconds
#Set duration in milliseconds
startTimes = [] 

for s in startSec:
    startTime = s*1000 
    startTimes.append(startTime) 

endTimes = []

for e in endSec:
    endTime = e*1000 
    endTimes.append(endTime)
for s, e in startTimes, endTimes:
    for f in files:
        song = AudioSegment.from_wav(path+'\\'+ f)
        extract = song[s:e]
        extract.export(f+'-extract.mp3', format="mp3")

Does anyone have any idea what mistake I might be making to have these empty files?

Note: this is my first experience with this library, so I don't know if this is the best tool or the best way to implement a solution

Another version:

for f in files:
    song = AudioSegment.from_wav(path+'\\'+ f)
    extract = song[startTime:endTime]
    extract.export(f+'-extract.mp3', format="mp3")

Changing the last loop, I got the two files, but both start according to the defined second starting point (15 seconds), instead of the first starting at 20 and the second at 15.


Solution

  • If you check the output of your last (outer) loop in the original version -

    for s, e in startTimes, endTimes:
        print(s, e)
    

    you'll see that the output is

    20000 15000

    50000 45000
    so you get wrong start and end times.
    The correct way to itetrate over the two lists is by using the zip() function -

    for s, e in zip(startTimes, endTimes):
        print(s, e)
    

    which yields:
    20000 50000
    15000 45000

    So your loop should look like this -

    for f, s, e in zip(files, startTimes, endTimes):
        song = AudioSegment.from_wav(path+'\\'+ f)
        extract = song[s:e]
        extract.export(f+'-extract.mp3', format="mp3")