Skip to content

Instantly share code, notes, and snippets.

@dgrant
Last active December 14, 2015 23:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dgrant/5164561 to your computer and use it in GitHub Desktop.
Save dgrant/5164561 to your computer and use it in GitHub Desktop.
This script will create mp3 sample clips.
#!/usr/bin/env python
"""A utility for creating a clip of an mp3 file"""
import getopt, os, sys
from subprocess import Popen, PIPE
try:
from mutagen.id3 import ID3
except ImportError:
print "Missing mutagen. On Debian systems, install python-mutagen"
sys.exit(1)
def copyid3(src, dst):
""" Copy the id3 tag from the src file to the dst file """
id3 = ID3(src)
id3.save(dst, v1=0)
def mp3towav(mp3filename, wavfilename):
""" Convert mp3filename to a wav file, wavfilename """
pid = Popen(["mpg123", "-w", wavfilename, mp3filename], stdout=PIPE,
stderr=PIPE)
return pid.communicate()[0]
def cutwav(wavfilename, cutwavfilename, endtime):
""" Cut wavfilename """
pid = Popen(["qwavcut", "-s", endtime, "-o", cutwavfilename, wavfilename],
stderr=PIPE, stdout=PIPE)
return pid.communicate()[0]
def fadeoutwav(wavfilename, duration):
""" Fade out wavfilename by duration """
pid = Popen(["qwavfade", "-l", duration, "-o", wavfilename],
stderr=PIPE, stdout=PIPE)
return pid.communicate()[0]
def encodemp3(wavfilename, mp3filename, bitrate):
""" Encode wav file wavfilename into an mp3, mp3filename """
pid = Popen(["lame", "-b", bitrate, wavfilename, mp3filename],
stderr=PIPE, stdout=PIPE)
return pid.communicate()[0]
def run(outdir, endtime, fadeout, files):
"""
Process "files". Fade them out by "fadeout" time after "endTime"
Copy resulting samples to outdir
"""
#make new directory to store them in
if outdir != None:
if not os.path.isdir(outdir):
os.mkdir(outdir)
#For each file
for mp3filename in files:
mp3filename = os.path.abspath(mp3filename)
baseabsname, ext = os.path.splitext(mp3filename)
basedir, basename = os.path.split(mp3filename)
basename = os.path.splitext(basename)[0]
#make sure it's an mp3
if ext != '.mp3':
break
wavfilename = baseabsname+'.wav'
if os.path.isfile(wavfilename):
print "%s already exists?" % (wavfilename)
return
try:
print "Working on %s" % (basename)
#convert to wav
mp3towav(mp3filename, wavfilename)
#cut the wav (overwrite original is fine)
cutwavfilename = baseabsname+'_cut_'+'.wav'
cutwav(wavfilename, cutwavfilename, endtime)
#fade it (overwrite original is fine)
fadeoutwav(cutwavfilename, fadeout)
#encode temp wav to mp3 in the new directory
newmp3filename = os.path.join(outdir if outdir else basedir,
basename+'_sample.mp3')
encodemp3(cutwavfilename, newmp3filename, '128')
#insert id3 object
copyid3(mp3filename, newmp3filename)
finally:
os.remove(wavfilename)
os.remove(cutwavfilename)
def usage():
""" print out usage for command line use """
print "createMP3Snippet.py [-o|--outdir <output directory>] [-h|--help]"
print " [-c|--cut <point to cut off>]"
print " [-f|--fadeout <fade out duration>]"
print " <file pattern to process>"
def main():
""" main program, only in here should we call sys.exit """
try:
opts, args = getopt.getopt(sys.argv[1:],
"o:hc:f:", ["outdir", "help", "cut", "fadeout"])
except getopt.GetoptError, err:
print str(err)
usage()
sys.exit(2)
outdir = None
cut = "30s"
fadeout = "5s"
for option, argument in opts:
if option in ("-o", "--outdir"):
outdir = argument
elif option in ("-h", "--help"):
usage()
sys.exit()
elif option in ("-c", "--cut"):
cut = argument
elif option in ("-f", "--fadeout"):
fadeout = argument
else:
assert False, "unhandled option"
run(outdir, cut, fadeout, args)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment