👷🏻‍♀️ determine length of mp3s via mutagen, not by file size

master
neingeist 3 years ago
parent 1d173aa45a
commit a18c1706c0

@ -2,6 +2,8 @@ import os
import random
import string
from datetime import datetime, timedelta
from functools import lru_cache
from mutagen.mp3 import MP3
def random_choices(population, k):
@ -9,23 +11,23 @@ def random_choices(population, k):
return [random.choice(population) for _ in range(k)]
def mp3_sources(data_dir, pattern, kbits):
def mp3_sources(data_dir, pattern):
def start_time_for_source_fn(fn):
return datetime.strptime(fn, pattern)
return datetime.strptime(os.path.basename(fn), pattern)
@lru_cache(maxsize=None)
def length_for_source_fn(fn):
size = os.stat(os.path.join(data_dir, fn)).st_size
length = timedelta(minutes=size / (1000*kbits/8) / 60)
return length
return timedelta(seconds=MP3(fn).info.length)
def get_sources():
# Get a sorted list of all source files with start time and length
sources = []
for fn in os.listdir(data_dir):
fn = os.path.join(data_dir, fn)
try:
start_time = start_time_for_source_fn(fn)
length = length_for_source_fn(fn)
sources.append({'fn': os.path.join(data_dir, fn), 'start_time': start_time, 'length': length})
sources.append({'fn': fn, 'start_time': start_time, 'length': length})
except ValueError:
pass
return sources
@ -50,10 +52,9 @@ class Config:
# [ {"fn": "/path/to/foo-20:01.mp3", "start_time": datetime(...), "length": timedelta(hours=1)} ]
data_dir = os.environ.get('DATA_DIR') or '/var/tmp/prolefeeder-test-data'
kbits = os.environ.get('KBITS') or 128
pattern = 'qfhi-%Y%m%d-%H%M.mp3'
if not os.path.exists(data_dir):
raise RuntimeError("DATA_DIR does not exist")
SOURCES = mp3_sources(data_dir, pattern, kbits)
SOURCES = mp3_sources(data_dir, pattern)

@ -10,7 +10,7 @@ def generate_test_file(fn, delta):
'ffmpeg',
'-f', 'lavfi',
'-i', 'sine=frequency=1000:duration=%d' % delta.total_seconds(),
'-b:a', '%dk' % Config.kbits,
'-b:a', '%dk' % 128,
fn
])

@ -3,7 +3,7 @@ import os
def application(req_environ, start_response):
# Work around having no access to Apache SetEnv variables:
for k in ['SECRET_KEY', 'DATA_DIR', 'TMP_DIR', 'MAX_LENGTH', 'KBITS']:
for k in ['SECRET_KEY', 'DATA_DIR', 'TMP_DIR', 'MAX_LENGTH']:
if k in req_environ:
os.environ[k] = req_environ[k]

@ -3,3 +3,4 @@ bootstrap-flask
python-dotenv
flask-wtf >= 1.0.0
WTForms >= 3.0.0
mutagen

Loading…
Cancel
Save