-
-
Save wilson0x4d/e5603d2d33f0b88f89754a8829754ab5 to your computer and use it in GitHub Desktop.
bulk transcode to MP3 using multiple cores (relies on `ffmpeg`)
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
#!/usr/bin/env python3 | |
""" | |
Transcodes list of audio files specified as command-line arguments into | |
standard MP3s. Example: | |
```bash | |
./convert_to_mp3.py *.m4a | |
``` | |
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. | |
Taken from the public domain. | |
Credit for Python 2 version goes to Chris Hiszpanski (https://github.com/hiszpanski). | |
Credit for Python 3 version goes to Shaun Wilson (https://github.com/wilson0x4d). | |
""" | |
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(f"{multiprocessing.current_process().name} : converting {fileurl}") | |
# 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment