Skip to content

Instantly share code, notes, and snippets.

@meoow meoow/ffmp3.py
Created Oct 24, 2014

Embed
What would you like to do?
A wrapper for FFmpeg to convert any support media file to high quality MP3 file.
#!/usr/bin/env python2.7
from optparse import OptionParser
from subprocess import call,Popen, PIPE
from os.path import splitext
import sys, os, re
def mediainfo(filename):
bitratePtn = re.compile(r'^\s*Duration:.+, (bitrate: (\d+) kb/s).*$')
videoPtn = re.compile(r'^\s*Stream #\d+:\d+.*?: Video: ([^,]+).*$')
audioPtn = re.compile(r'^\s*Stream #\d+:\d+.*?: Audio: ([^,]+).*$')
resolutionPtn = re.compile(r'^.*?(\d{1,4}x\d{1,4})[, ].*$')
hzPtn = re.compile(r'^.*?(\d+ Hz).*$')
sbitratePtn = re.compile(r'^.*?(\d+ kb/s).*$')
fpsPtn = re.compile(r'^.*?(\d+(\.\d+)?) fps,.*$')
bitrate = ''
vbitrate = ''
abitrate = ''
resolution = ''
vcodec = ''
acodec = ''
hz = ''
fps = ''
cmd = Popen(['ffmpeg', '-hide_banner','-i', filename], stdout = PIPE, stderr = PIPE)
for l in cmd.stderr:
l = l.strip()
if not bitrate:
a = bitratePtn.match(l)
if a:
bitrate = a.group(2)
continue
if not vcodec:
a = videoPtn.match(l)
if a:
vcodec = a.group(1).split()[0]
try:
resolution = resolutionPtn.match(l).group(1).split('x')
except AttributeError:
pass
try:
vbitrate = sbitratePtn.match(l).group(1).split()[0]
except AttributeError:
pass
try:
fps = fpsPtn.match(l).group(1).split()[0]
except AttributeError:
pass
continue
if not acodec:
a = audioPtn.match(l)
if a:
acodec = a.group(1).split()[0]
try:
hz = hzPtn.match(l).group(1).split()[0]
except AttributeError:
pass
try:
abitrate = sbitratePtn.match(l).group(1).split()[0]
except AttributeError:
pass
continue
cmd.wait()
return {'bitrate':bitrate, "vcodec":vcodec, 'resolution':resolution,
'vbitrate':vbitrate, 'fps':fps,
"acodec":acodec, "sampling":hz, 'abitrate':abitrate}
def ffmp3(filename, quality):
if filename.lower().endswith('.mp3'):
return
if quality.startswith('q'):
qopt = '-q:a'
qval = quality.lstrip('q')
else:
qopt = '-b:a'
if quality.endswith('k'):
qval = quality
else:
qval = quality + 'k'
outfile = splitext(filename)[0] + '.mp3'
cmd = ['ffmpeg', '-hide_banner', '-y', '-i', filename,
'-c:a', 'libmp3lame','-compression_level','0', '-abr', '1',
qopt, qval]
mi = mediainfo(filename)
if mi['sampling'] and int(mi['sampling']) > 44100:
cmd.extend(['-ar', '44100'])
cmd.extend(['-c:v','mjpeg','-filter:v','scale=\'min(512,iw):-2\'','-id3v2_version', '4', '-f','mp3',outfile])
return call(cmd)
if __name__=='__main__':
parser = OptionParser(sys.argv[0]+' -q <qNUM|NUM[k]> FILE1 [FILE2 ...]')
parser.add_option('-q', metavar='NUM', dest='qual (eg. 0q, 2q, 256k or 320k)')
parser.add_option('-d', action='store_true', dest='delete')
opts, args = parser.parse_args()
for f in args:
if ffmp3(f, opts.qual) == 0 and opts.delete :
try:
os.remove(f)
except OSError:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.