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

This commit is contained in:
neingeist 2021-12-07 10:20:57 +01:00
parent 1d173aa45a
commit a18c1706c0
4 changed files with 12 additions and 10 deletions

View file

@ -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)