[Python] How can I find the decibel of music or video that comes out of my device python

Discussão em 'Python' iniciado por Stack, Maio 24, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to build a simple live decibel meter in Python using the sounddevice and numpy libraries. The idea is to list input devices, let the user choose one, and then print dB levels continuously from the device.

    However, when I run the script, nothing happens — there are no errors, but also no output. It just silently exits or seems stuck. I suspect the decibel loop isn't starting, but I don't see why.

    Here's the script:

    import sounddevice as sd
    import numpy as np
    import time

    # --- Einstellungen ---
    SAMPLERATE = 48000 # Samplerate (in Hz)
    INTERVAL = 0.5 # Alle 0.5 Sekunden messen

    def db_from_rms(rms):
    """Berechne Dezibel aus RMS"""
    if rms == 0:
    return -np.inf
    return 20 * np.log10(rms)

    def live_db_meter(device_id):
    """Live-Systemaudio vom Mikrofon aufnehmen und Dezibel anzeigen"""
    with sd.InputStream(
    device=device_id, # Das Eingabegerät (z.B. Mikrofon)
    channels=1, # Mono-Kanal für das Mikrofon (1 Kanal)
    samplerate=SAMPLERATE,
    dtype='float32',
    latency='low'
    ) as stream:
    print("Starte Dezibelmessung... (Drücke STRG+C zum Beenden)\n")
    try:
    while True:
    audio, _ = stream.read(int(SAMPLERATE * INTERVAL)) # Lese die Audiodaten
    rms = np.sqrt(np.mean(audio**2)) # Berechne den RMS-Wert
    db = db_from_rms(rms) # Berechne Dezibel aus RMS
    print(f"Dezibel: {db:.2f} dB", end="\r") # Zeige den Dezibelwert in der gleichen Zeile an
    time.sleep(0.01)
    except KeyboardInterrupt:
    print("\nMessung beendet.")

    # Geräte auflisten und auswählen
    def list_devices():
    """Zeige alle verfügbaren Audiogeräte"""
    devices = sd.query_devices()
    if len(devices) == 0:
    print("Keine Geräte gefunden!")
    else:
    print("Verfügbare Geräte:\n")
    for idx, device in enumerate(devices):
    print(f"{idx}: {device['name']}")

    # Hauptteil des Programms
    if __name__ == "_main_":
    print("Verfügbare Geräte werden geladen...\n")
    list_devices() # Zeige alle verfügbaren Geräte an

    try:
    device_id = int(input("\nGib die Nummer des Geräts ein: ")) # Geräte-ID vom Nutzer abfragen
    live_db_meter(device_id) # Starte die Dezibelmessung
    except ValueError:
    print("Ungültige Eingabe! Bitte eine gültige Geräte-ID eingeben.")

    Continue reading...

Compartilhe esta Página