Skip to content

Commit

Permalink
get_integrated_lufs now concatenates files <0.5 before computing LUFS
Browse files Browse the repository at this point in the history
To avoid getting constant -70.0 for files shorter than 400 ms
  • Loading branch information
justinsalamon committed Jul 21, 2018
1 parent 37a80ee commit 65ecaff
Showing 1 changed file with 52 additions and 3 deletions.
55 changes: 52 additions & 3 deletions scaper/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
'''

import subprocess
import sox
import numpy as np
import tempfile
from .scaper_exceptions import ScaperError
from .util import _close_temp_files


def r128stats(filepath):
Expand Down Expand Up @@ -50,8 +54,53 @@ def r128stats(filepath):
return stats_dict


def get_integrated_lufs(filepath):
'''Returns the integrated lufs for an audiofile'''
def get_integrated_lufs(filepath, min_duration=0.5):
"""
Returns the integrated LUFS for an audiofile.
For files shorter than 400 ms ffmpeg returns a constant integrated LUFS
value of -70.0. To avoid this, files shorter than min_duration (by default
500 ms) are self-concatenated until min_duration is reached and the
LUFS value is computed for the concatenated file.
Parameters
----------
filepath : str
Path to audio file for computing LUFS
min_duration : float
Minimum required duration for computing LUFS value. Files shorter than
this are self-concatenated until their duration reaches this value
for the purpose of computing the integrated LUFS. Caution: if you set
min_duration < 0.4, a constant LUFS value of -70.0 will be returned for
all files shorter than 400 ms.
Returns
-------
"""
try:
duration = sox.file_info.duration(filepath)
except Exception as e:
raise ScaperError(
'Unable to obtain LUFS for {:s}, error message:\n{:s}'.format(
filepath, e.__str__()))

if duration < min_duration:
# compute how many concatenations we require
n_tiles = int(np.ceil(min_duration / duration))

# Concatenate audio to itself, save to temp file and get LUFS
tmpfiles = []
with _close_temp_files(tmpfiles):
concat_file = tempfile.NamedTemporaryFile(suffix='.wav',
delete=True)
tmpfiles.append(concat_file)

cbn = sox.Combiner()
cbn.build([filepath] * n_tiles, concat_file.name, 'concatenate')

loudness_stats = r128stats(concat_file.name)
else:
loudness_stats = r128stats(filepath)

loudness_stats = r128stats(filepath)
return loudness_stats['I']

0 comments on commit 65ecaff

Please sign in to comment.