Created
October 24, 2014 06:40
-
-
Save meoow/41be32c8675a2dd84cc7 to your computer and use it in GitHub Desktop.
Embed ablum cover into MP3 file using FFmpeg
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2.7 | |
from optparse import OptionParser | |
from subprocess import call | |
import os.path | |
import os | |
import tempfile | |
img_max_width_or_height = 256 | |
def ffcover(filename, cover, right): | |
cwd = os.path.dirname(filename) | |
tmpfile = tempfile.mktemp(dir=cwd) | |
if right: | |
axis_x = 'iw-min(iw,ih)' | |
axis_y = 'ih-min(iw,ih)' | |
else: | |
axis_x='0' | |
axis_y='0' | |
cmd = [ 'ffmpeg', '-hide_banner', '-y', '-i', filename, '-i', cover, | |
'-map', '0:a', '-map', '1:v', | |
'-c:a', 'copy', '-id3v2_version', '3', | |
'-c:v', 'mjpeg', | |
'-filter:v', | |
'scale=\'if(eq(if(gte(iw,ih),iw,-2),-2),-2,min(iw,{0})):if(eq(if(gt(ih,iw),ih,-2),-2),-2,min(ih,{0}))\',crop=\'min(iw,ih):min(iw,ih):{1}:{2}\''.format(img_max_width_or_height, axis_x, axis_y), | |
'-metadata:s:v', 'title=Album Cover', | |
'-metadata:s:v', 'comment=Cover (Front)', | |
'-f', 'mp3', | |
tmpfile ] | |
try: | |
ret = call(cmd,stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w')) | |
if ret == 0: | |
os.rename(tmpfile, filename) | |
finally: | |
if os.path.exists(tmpfile): | |
os.remove(tmpfile) | |
if __name__=='__main__': | |
parser = OptionParser('ffcover.py -c COVER FILE1 [FILE2 ...]') | |
parser.add_option('-c', metavar='FILE', dest='cover', help='Cover file.') | |
parser.add_option('-r', action='store_true', dest='right') | |
opts, args = parser.parse_args() | |
for f in args: | |
ffcover(f, opts.cover, opts.right) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment