calc_decibel.py
1.03 KB
import pyaudio
import numpy as np
# Define constants
CHUNK_SIZE = 1024 # Number of audio frames per buffer
FORMAT = pyaudio.paInt16 # Audio format (16-bit int)
CHANNELS = 1 # Mono audio
RATE = 44100 # Sample rate (Hz)
RMS_REF = 1.0 # Reference RMS amplitude for dB calculation
# Initialize PyAudio stream
audio = pyaudio.PyAudio()
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK_SIZE)
# Main loop
while True:
# Read audio data from stream
data = stream.read(CHUNK_SIZE)
# Convert audio data to numpy array
audio_array = np.frombuffer(data, dtype=np.int16)
# Calculate RMS amplitude
rms = np.sqrt(np.mean(np.square(audio_array)))
# Calculate dB level
avg_db = 20 * np.log10(rms / RMS_REF)
max_db = 20 * np.log10(np.max(audio_array) / RMS_REF)
# Print dB level to console
try:
if(avg_db != np.NaN and max_db != np.NaN and max_db > 50):
print("dB level:", int(avg_db), int(max_db))
except:
continue