view itunes2mp3.py @ 2:1681a628ceb4

Pass desired bit rate in the right place otherwise newer FFmpeg's complain.
author Daniel O'Connor <darius@dons.net.au>
date Mon, 18 Aug 2014 13:38:06 +0930
parents 0ca90a90e723
children 30f4a5616692
line wrap: on
line source

#!/usr/bin/env python

import errno
import glob
import os
import plistlib
import random
import shutil
import subprocess
import sys
import urllib2

def compress(srcfile, destdir):
    plist = plistlib.readPlist(srcfile)
    playlist = plist['Playlists'][0]
    
    failures = []
    for item in playlist['Playlist Items']:
        track = plist['Tracks'][str(item['Track ID'])]
        if 'Location' not in track:
            print "No location for " + track['Name']
            continue

        location = track['Location']

        path = urllib2.unquote(urllib2.urlparse.urlparse(location).path)
        print "Path is " + path

        destmp3 = destdir + '/' + path.split('/')[-1][:-3] + 'mp3'
        if os.path.isfile(destmp3):
            print "Already done"
            continue
        
        devnull = file('/dev/null', 'w')
        if path.lower().endswith('.mp3'):
            shutil.copy(path, destmp3)
        elif path.lower().endswith('.m4a'):
            ffmpeg = subprocess.Popen(['ffmpeg', '-y', '-v', 'quiet', '-i', path, '-b', '160', destmp3])
            rtn = ffmpeg.wait()

            if rtn != 0:
                print "Failed to convert %s, return code %d" % (path, rtn)
                failures.append(path)
                try:
                    os.unlink(destmp3)
                except OSError, e:
                    if e.errno != 2:
                        raise e
        else:
            print "Don't know how to convert " + path
    if len(failures) > 0:
        print
        print "Failures:"
    for f in failures:
        print f

def shuffle(srcdir):
    try:
        os.mkdir(srcdir + '/burn')
    except OSError, e:
        if e.errno != 17:
            raise e
    files = glob.glob(srcdir + '/*.mp3')
    random.shuffle(files)

    i = 0
    for f in files:
        dest = srcdir + '/burn/%03d - %s' % (i, f.split('/')[-1])
        i += 1
        os.link(f, dest)
    
if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Bad usage"
        print "%s playlist.xml destdir"
        sys.exit(1)

    compress(sys.argv[1], sys.argv[2])
    shuffle(sys.argv[2])