Skip to content

Instantly share code, notes, and snippets.

@tristan0x
Last active April 25, 2020 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tristan0x/10c06fe5a65e4d202615686bbd3341d2 to your computer and use it in GitHub Desktop.
Save tristan0x/10c06fe5a65e4d202615686bbd3341d2 to your computer and use it in GitHub Desktop.
"""Script used to extract audio tracks from MP4 videos to MP3
with ffmpeg. The script processes multiple files simultaneously.
Examples:
# To extract the audio track from my-video.mp4
# and write it in my-videos.mp3:
python3 mp4tomp3.py my-video.mp4
# the script accepts multiple arguments
python3 mp4tomp3.py my-video1.mp4 my-video2.mp4
# pass a directory to the script to convert all MP4 videos
# contained in this directory (not recursive)
python3 mp4tomp3.py my-directory/
"""
import argparse
import multiprocessing
from pathlib import Path
import subprocess
import sys
def convert_mp4(mp4):
mp3 = str(mp4)[:-4] + ".mp3"
command = ["ffmpeg", "-i", mp4, mp3]
subprocess.run(command)
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-p",
"--processes",
help="Specifies the number of conversions to run simultaneously (default is %(default)s)",
default=multiprocessing.cpu_count(),
)
parser.add_argument(
"PATH", help="MP4 file to convert or directory containing MP4 files to convert", nargs='+'
)
args = parser.parse_args()
# gather all the files to be converted
tasks = set()
for path in args.PATH:
path = Path(path).resolve()
if not path.exists():
print("Error: path does not exists: ", path, file=sys.stderr)
sys.exit(1)
if path.is_dir():
for mp4 in path.glob("*.mp4"):
tasks.add(mp4)
else:
tasks.add(path)
# execute the conversion in a pool of processes
with multiprocessing.Pool(args.processes) as pool:
pool.map(convert_mp4, tasks)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment