1

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.

2
  • 1. pydub is using ffmpeg, so make sure you've got it installed right and that you are using the right version. 2. You don't really need to add 0*60*1000 in startTime or endTime to convert from seconds to mSeconds :) Commented Oct 31, 2021 at 18:41
  • Hi, @TDG. I have ffmpeg installed. I can trim a single file, but what I haven't been able to do is get the correct start for each one, when I consider multiple files. In another version, for example, I trimmed the two files, but only with the last starting point for both (15 seconds). I believe I'm making a mistake by passing the desired beginnings in extract = song[s:e]. Commented Oct 31, 2021 at 18:55

1 Answer 1

1

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") 
Sign up to request clarification or add additional context in comments.

2 Comments

Pls check my edited answer.
Exactly! Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.