Skip to content

Instantly share code, notes, and snippets.

@hiszpanski
Created October 29, 2012 22:26
Show Gist options
  • Save hiszpanski/3976945 to your computer and use it in GitHub Desktop.
Save hiszpanski/3976945 to your computer and use it in GitHub Desktop.
Bulk transcoding of files to MP3 using multiple cores and FFMPEG
#!/usr/bin/env python
"""
Transcodes list of audio files specified as command-line arguments into
standard MP3s.
Actual transcoding is done via a subprocess call to ffmpeg. If multiple
cores are available, transcoding is parallelized via a pool of workers, each
of which transcodes one file at a time.
"""
import multiprocessing
import os
import signal
import subprocess
import sys
def init_worker():
signal.signal(signal.SIGINT, signal.SIG_IGN)
def worker(fileurl):
# Print informational message
print multiprocessing.current_process().name,
print ': converting ', fileurl
sys.stdout.flush()
# Derive output filename
(root, ext) = os.path.splitext(fileurl)
outfile = root + ".mp3"
# If output file exists, break out
if os.path.exists(outfile):
return
# Call out to ffmpeg
subprocess.call(["ffmpeg", "-y", "-loglevel", "quiet", "-i", \
fileurl, outfile])
if __name__ == '__main__':
# Create a pool of workers (equal to number returned by cpu_count())
pool = multiprocessing.Pool(initializer=init_worker)
# Map conversion of files to pool of workers. Skip the program name itself.
try:
pool.map(worker, sys.argv[1:])
except KeyboardInterrupt:
print "Caught KeyboardInterrupt, terminating"
pool.terminate()
pool.join()
@denis-trofimov
Copy link

denis-trofimov commented Apr 28, 2018

That is beatiful. Reused your code in my Bulk transcoding of video files using multiple cores and FFMPEG. Thanks, @thinkski!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment