Normalise mp3's on import

This commit is contained in:
Keith Edmunds 2021-07-15 17:54:34 +01:00
parent 2edf12670f
commit 4f10ed7bad

View File

@ -9,6 +9,7 @@ from config import Config
from log import DEBUG, INFO from log import DEBUG, INFO
from model import Tracks, Playdates, PlaylistTracks, Session from model import Tracks, Playdates, PlaylistTracks, Session
from mutagen.flac import FLAC from mutagen.flac import FLAC
from mutagen.mp3 import MP3
from pydub import AudioSegment, effects from pydub import AudioSegment, effects
from tinytag import TinyTag from tinytag import TinyTag
@ -68,6 +69,12 @@ def create_track_from_file(session, path):
session.commit() session.commit()
if Config.NORMALISE_ON_IMPORT: if Config.NORMALISE_ON_IMPORT:
# Check type
ftype = os.path.splitext(path)[1][1:]
if ftype not in ['mp3', 'flac']:
INFO(f"File type {ftype} not implemented")
return track
# Get current file gid, uid and permissions # Get current file gid, uid and permissions
stats = os.stat(path) stats = os.stat(path)
try: try:
@ -78,26 +85,32 @@ def create_track_from_file(session, path):
DEBUG(f"songdb.create_track_from_file({path}): err1: {str(err)}") DEBUG(f"songdb.create_track_from_file({path}): err1: {str(err)}")
return return
# Overwrite original file with normalised output # Overwrite original file with normalised output
normalised = effects.normalize(audio) normalised = effects.normalize(audio)
try: try:
normalised.export(path, format=os.path.splitext(path)[1][1:]) normalised.export(path, format=os.path.splitext(path)[1][1:])
# Fix up permssions and ownership # Fix up permssions and ownership
os.chown(path, stats.st_uid, stats.st_gid) os.chown(path, stats.st_uid, stats.st_gid)
os.chmod(path, stats.st_mode) os.chmod(path, stats.st_mode)
# Copy tags # Copy tags
src = FLAC(temp_path) if ftype == 'flac':
dst = FLAC(path) tag_handler = FLAC
for tag in src: elif ftype == 'mp3':
dst[tag] = src[tag] tag_handler = MP3
dst.save() else:
except Exception as err: return track
DEBUG(f"songdb.create_track_from_file({path}): err2: {str(err)}") src = tag_handler(temp_path)
# Restore original file dst = tag_handler(path)
shutil.copyfile(path, temp_path) for tag in src:
finally: dst[tag] = src[tag]
if os.path.exists(temp_path): dst.save()
os.remove(temp_path) except Exception as err:
DEBUG(f"songdb.create_track_from_file({path}): err2: {str(err)}")
# Restore original file
shutil.copyfile(path, temp_path)
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
return track return track
@ -105,7 +118,7 @@ def create_track_from_file(session, path):
def full_update_db(): def full_update_db():
"Rescan all entries in database" "Rescan all entries in database"
pass print("Full scan not yet implemented")
def get_audio_segment(path): def get_audio_segment(path):