This is a nice script for monitoring currently playing MP3 files and extracting their lyrics for display (looks like it's for OBS streaming). Here are some observations and potential improvements:
What the script does well:
- Simple and focused on its task
- Good error handling with try/except blocks
- Cleans up lyrics text by removing control characters
- Uses file access time (
os.path.getatime) to detect which song is currently playing
Potential improvements:
- Performance optimization - Instead of calling
glob.glob() every 3 seconds, you could cache the file list and only update when the directory's modification time changes:
def hole_zuletzt_geaenderte_mp3(cache={}):
dir_mtime = os.path.getmtime(musik_ordner)
if 'mtime' not in cache or cache['mtime'] != dir_mtime:
cache['mtime'] = dir_mtime
cache['files'] = glob.glob(os.path.join(musik_ordner, "*.mp3"))
if not cache['files']:
return None
cache['files'].sort(key=lambda x: os.path.getatime(x), reverse=True)
return cache['files'][0]
- Handle missing eyed3 tags better - Some MP3s might not have proper tags:
def hole_lyrics(mp3_pfad):
try:
audio = eyed3.load(mp3_pfad)
if not audio or not audio.tag:
return "Keine MP3-Tags gefunden"
# Also check for title/artist info
titel = audio.tag.title or "Unbekannt"
artist = audio.tag.artist or "Unbekannt"
if audio.tag.lyrics:
lyrics = audio.tag.lyrics[0].text
lyrics = lyrics.replace('\r\n', '\n').replace('\r', '\n')
lyrics = ''.join(char for char in lyrics if ord(char) >= 32 or char in '\n\t')
return f"{artist} - {titel}\n\n{lyrics}"
return f"{artist} - {titel}\n\nKeine Lyrics gefunden"
except Exception as e:
return f"Fehler: {e}"
- Add configuration options at the top:
# Konfiguration
MUSIK_ORDNER = "C:\\Musik\\1"
LYRICS_DATEI = "C:\\OBS\\zyphens-now-playing-master\\lyrics.txt"
AKTUALISIERUNGS_INTERVALL = 3 # Sekunden
-
Consider using file modification time instead of access time - Some systems don't reliably update access time, or it might be disabled for performance reasons. You might want to use os.path.getmtime() instead.
-
Add a timestamp to know when the song started playing:
from datetime import datetime
# In der Hauptschleife:
spielzeit = datetime.now().strftime("%H:%M:%S")
print(f"🎵 [{spielzeit}] Aktuell: {dateiname}")
The script should work well for its intended purpose of providing live lyrics display in OBS!