2021-08-16 22:43:09 +00:00
|
|
|
import os
|
2021-09-11 15:49:08 +00:00
|
|
|
from pydub import AudioSegment, effects # Audio leveling!
|
2021-08-16 22:43:09 +00:00
|
|
|
|
|
|
|
# Stuff to help make BAPSicle play out leveled audio.
|
|
|
|
|
2021-08-17 21:04:20 +00:00
|
|
|
# Takes filename in, normalialises it and returns a normalised file path.
|
2021-09-11 16:48:57 +00:00
|
|
|
|
|
|
|
|
2021-08-16 22:43:09 +00:00
|
|
|
def generate_normalised_file(filename: str):
|
2021-09-11 15:49:08 +00:00
|
|
|
if not (isinstance(filename, str) and filename.endswith(".mp3")):
|
|
|
|
raise ValueError("Invalid filename given.")
|
2021-08-16 22:43:09 +00:00
|
|
|
|
2021-09-11 15:49:08 +00:00
|
|
|
# Already normalised.
|
|
|
|
if filename.endswith("-normalised.mp3"):
|
|
|
|
return filename
|
2021-08-16 22:43:09 +00:00
|
|
|
|
2021-09-11 15:49:08 +00:00
|
|
|
normalised_filename = "{}-normalised.mp3".format(filename.rsplit(".", 1)[0])
|
2021-08-16 22:43:09 +00:00
|
|
|
|
2021-09-11 15:49:08 +00:00
|
|
|
# The file already exists, short circuit.
|
|
|
|
if os.path.exists(normalised_filename):
|
|
|
|
return normalised_filename
|
2021-08-16 22:43:09 +00:00
|
|
|
|
2021-09-11 15:49:08 +00:00
|
|
|
sound = AudioSegment.from_file(filename, "mp3")
|
|
|
|
normalised_sound = effects.normalize(sound)
|
2021-08-16 22:43:09 +00:00
|
|
|
|
2021-09-11 15:49:08 +00:00
|
|
|
normalised_sound.export(normalised_filename, bitrate="320k", format="mp3")
|
|
|
|
return normalised_filename
|
2021-08-16 22:43:09 +00:00
|
|
|
|
|
|
|
|
2021-09-11 15:49:08 +00:00
|
|
|
# Returns either a normalised file path (based on filename), or the original if not available.
|
|
|
|
def get_normalised_filename_if_available(filename: str):
|
|
|
|
if not (isinstance(filename, str) and filename.endswith(".mp3")):
|
|
|
|
raise ValueError("Invalid filename given.")
|
2021-08-16 22:43:09 +00:00
|
|
|
|
2021-09-11 15:49:08 +00:00
|
|
|
# Already normalised.
|
|
|
|
if filename.endswith("-normalised.mp3"):
|
|
|
|
return filename
|
2021-08-16 22:43:09 +00:00
|
|
|
|
2021-09-11 15:49:08 +00:00
|
|
|
normalised_filename = "{}-normalised.mp3".format(filename.rstrip(".mp3"))
|
2021-08-16 22:43:09 +00:00
|
|
|
|
2021-09-11 15:49:08 +00:00
|
|
|
# normalised version exists
|
|
|
|
if os.path.exists(normalised_filename):
|
|
|
|
return normalised_filename
|
2021-08-16 22:43:09 +00:00
|
|
|
|
2021-09-11 15:49:08 +00:00
|
|
|
# Else we've not got a normalised verison, just take original.
|
|
|
|
return filename
|