Add mp3 converter
This commit is contained in:
parent
65380e5f12
commit
f0430f8713
1 changed files with 77 additions and 0 deletions
77
src/music/convert.py
Normal file
77
src/music/convert.py
Normal file
|
@ -0,0 +1,77 @@
|
|||
import argparse
|
||||
import os
|
||||
import logging
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from multiprocessing import Pool
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def launch_task(cmd):
|
||||
subprocess.run(cmd, shell=True, check=True)
|
||||
|
||||
def convert(input_dir: Path, output_dir: Path):
|
||||
|
||||
logger.info("Converting files in %s", input_dir)
|
||||
logger.info("Writing output to: %s", output_dir)
|
||||
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
flac_files = list(input_dir.resolve().rglob("*.flac"))
|
||||
tasks = []
|
||||
|
||||
for idx, path in enumerate(flac_files):
|
||||
|
||||
logger.info("Converting file %d of %d", idx, len(flac_files))
|
||||
|
||||
relative_path = path.relative_to(input_dir)
|
||||
output_filename = str(path.stem) + ".mp3"
|
||||
output_filename.replace("'", "")
|
||||
|
||||
output_path = output_dir / relative_path.parent / output_filename
|
||||
|
||||
cmd = f"ffmpeg -i '{path}' -ab 320k -map_metadata 0 -id3v2_version 3 '{output_path}'"
|
||||
tasks.append(cmd)
|
||||
|
||||
with Pool(10) as p:
|
||||
p.map(launch_task, tasks)
|
||||
|
||||
|
||||
def move(input_dir: Path, output_dir: Path):
|
||||
|
||||
logger.info("Moving files in %s to %s", input_dir, output_dir)
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
mp3_files = list(input_dir.resolve().rglob("*.mp3"))
|
||||
for idx, path in enumerate(mp3_files):
|
||||
logger.info("Moving file %d of %d", idx, len(mp3_files))
|
||||
relative_path = path.relative_to(input_dir)
|
||||
output_path = output_dir / relative_path
|
||||
os.makedirs(output_path.parent, exist_ok=True)
|
||||
shutil.move(path, output_path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
parser.add_argument('--input_dir',
|
||||
type=Path,
|
||||
default=Path(),
|
||||
help="Directory with input files for conversion.")
|
||||
|
||||
parser.add_argument('--output_dir',
|
||||
type=Path,
|
||||
default=Path(),
|
||||
help="Directory for converted files")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig()
|
||||
logging.getLogger().setLevel(logging.INFO)
|
||||
|
||||
# convert(args.input_dir.resolve(), args.output_dir.resolve())
|
||||
move(args.input_dir.resolve(), args.output_dir.resolve())
|
||||
|
||||
|
Loading…
Reference in a new issue