Skip to content

Instantly share code, notes, and snippets.

@srikarg
Created March 20, 2015 22:58
Show Gist options
  • Save srikarg/7ef9dca00d406eb0cafc to your computer and use it in GitHub Desktop.
Save srikarg/7ef9dca00d406eb0cafc to your computer and use it in GitHub Desktop.
This is an example of using pydub (http://pydub.com/) to trim a folder of songs from a given start time to end time specified in a text file.
import os
import pydub
pydub.AudioSegment.converter = '/usr/local/bin/ffmpeg'
songsDir = 'Original Songs'
trimmedDir = 'Trimmed Songs'
data = []
def trimSong(file, index):
values = data[index].split(',')
start = int(values[0]) * 1000
end = int(values[1]) * 1000
if not os.path.exists(trimmedDir):
os.makedirs(trimmedDir)
song = pydub.AudioSegment.from_mp3(os.path.join(songsDir, file))
song = song[start:end].fade_in(2000).fade_out(2000)
song = pydub.effects.normalize(song, 0.1)
song.export(os.path.join(trimmedDir, file), format='mp3')
with open('data.txt') as f:
for line in f:
data.append(line.rstrip('\n'))
for subdir, dirs, files in os.walk(songsDir):
index = -1
for file in files:
if file[-3:] != 'mp3':
continue
index += 1
trimSong(file, index)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment