Created
May 5, 2020 21:36
-
-
Save usbpc/fda53e7b6b98ceb2536b6cf60aafb3ff to your computer and use it in GitHub Desktop.
A Script to normalize the audio of media files while also converting them to mp3s
This file contains 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/python3 | |
#Tries to convert all the files in the directory where it is executed into normalized mp3s. | |
#All resulting mp3s are placed in a folder called 'normalized' | |
import multiprocessing as mp | |
import subprocess | |
import re | |
import json | |
import os | |
from os import listdir | |
from os.path import isfile, join | |
def convertFile(filename): | |
FILE_EXT_REGEX = re.compile(r'(.*)\..*') | |
JSON_REGEX = re.compile(r'{(.|\n)*}') | |
file_without_ext = FILE_EXT_REGEX.match(filename).group(1) | |
info_cmd = ["ffmpeg", "-hide_banner","-i", filename, "-af", "loudnorm=I=-16:TP=-1.5:LRA=11:print_format=json", "-f", "null", "-"] | |
cmd_out = subprocess.run(info_cmd, stderr=subprocess.PIPE) | |
out_string = cmd_out.stderr.decode('UTF-8') | |
try: | |
json_payload = JSON_REGEX.search(out_string).group(0) | |
except AttributeError: | |
return | |
data = json.loads(json_payload) | |
convert_cmd = ["ffmpeg", "-loglevel", "fatal", "-i", filename, "-af", f"loudnorm=I=-16:TP=-1.5:LRA=11:measured_I={data['input_i']}:measured_LRA={data['input_lra']}:measured_TP={data['input_tp']}:measured_thresh={data['input_thresh']}:offset={data['target_offset']}:linear=true:print_format=summary", f"./normalized/{file_without_ext}.mp3"] | |
subprocess.run(convert_cmd) | |
def runner(queue): | |
while not queue.empty(): | |
cur = queue.get(block=False) | |
if cur is not None: | |
convertFile(cur) | |
print(f'Converted "{cur}"') | |
print("Terminating a runner!") | |
try: | |
os.mkdir('normalized') | |
except: | |
print("normalized dir couldn't be created") | |
filenames = [f for f in listdir(os.getcwd()) if isfile(join(os.getcwd(), f))] | |
queue = mp.Queue() | |
for filename in filenames: | |
queue.put(filename) | |
#Change this to use less processes | |
thread_num = mp.cpu_count() | |
threads = list() | |
for i in range(0, thread_num): | |
print(f"Started process {i}") | |
process = mp.Process(target=runner, args=(queue,)) | |
process.start() | |
threads.append(process) | |
for thread in threads: | |
thread.join() | |
print("One process finished!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment