Created
June 4, 2013 08:44
-
-
Save madssj/5704554 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import os | |
import subprocess | |
import threading | |
from Queue import Queue | |
ITUNES_DIR = os.path.expanduser("~/Music/iTunes/iTunes Music/") | |
KNOWN_EXTENSIONS = ('.mp3', '.aac') | |
AACGAIN_PARAMS = ['-a', '-k', '-d', '3'] | |
AACGAIN_LOCATION = 'aacgain' | |
def get_files(): | |
""" | |
A generator that returns tuples with album name and a list of mp3 files. | |
""" | |
for root, dirs, files in os.walk(ITUNES_DIR): | |
files = filter(lambda x: os.path.splitext(x)[1] in KNOWN_EXTENSIONS, files) | |
if files: | |
yield [os.path.join(root, f) for f in files] | |
def get_num_cpus(): | |
""" | |
Returns the number of cpus in the machine, and 1 on failure. | |
""" | |
try: | |
return int(subprocess.Popen(['sysctl', '-n', 'hw.ncpu'], stdout=subprocess.PIPE).communicate()[0].strip()) | |
except: | |
return 1 | |
def run_aacgain(queue): | |
""" | |
Returns a callable that will be called inside a thread. | |
""" | |
def callable(): | |
try: | |
while True: | |
files = queue.get() | |
if files is None: | |
break | |
p = subprocess.Popen([AACGAIN_LOCATION] + AACGAIN_PARAMS + files) | |
p.wait() | |
except KeyboardInterrupt: | |
pass | |
return callable | |
queue = Queue() | |
workers = [] | |
for i in range(get_num_cpus()): | |
worker = threading.Thread(target=run_aacgain(queue)) | |
worker.start() | |
workers.append(worker) | |
for album_files in get_files(): | |
queue.put(album_files) | |
for i in range(get_num_cpus()): | |
queue.put(None) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment