45 lines
1.4 KiB
Python
45 lines
1.4 KiB
Python
import os
|
|
import subprocess
|
|
from pathlib import Path
|
|
from concurrent.futures import ProcessPoolExecutor, as_completed
|
|
import multiprocessing
|
|
|
|
def convert_file(filepath, out_dir):
|
|
filename = os.path.basename(filepath)
|
|
basename, _ = os.path.splitext(filename)
|
|
out_filename = basename + ".m4a"
|
|
out_path = os.path.join(out_dir, out_filename)
|
|
|
|
# ffmpeg command to copy audio
|
|
proc = subprocess.run(
|
|
["ffmpeg", "-i", filepath, "-vn", "-c:a", "copy", out_path],
|
|
capture_output=True
|
|
)
|
|
|
|
if proc.returncode != 0:
|
|
return f"ERROR: Failed to convert {filename}\n{proc.stderr.decode()}"
|
|
return f"Converted: {filename}"
|
|
|
|
def main():
|
|
cwd = Path.cwd()
|
|
in_dir = cwd / "playlists"
|
|
out_dir = cwd / "audios"
|
|
|
|
os.makedirs(out_dir, exist_ok=True)
|
|
|
|
files = [str(in_dir / f) for f in os.listdir(in_dir) if f.lower().endswith(('.mp4', '.mkv', '.mov'))]
|
|
|
|
# Use number of CPU cores, with 16 files max per core
|
|
num_cores = multiprocessing.cpu_count()
|
|
max_workers = min(len(files), num_cores)
|
|
|
|
print(f"Converting {len(files)} files using {max_workers} workers...")
|
|
|
|
results = []
|
|
with ProcessPoolExecutor(max_workers=max_workers) as executor:
|
|
futures = {executor.submit(convert_file, f, str(out_dir)): f for f in files}
|
|
for future in as_completed(futures):
|
|
print(future.result())
|
|
|
|
if __name__ == "__main__":
|
|
main() |