Home > Software engineering >  How would i find the current decibel level and set it as a variable?
How would i find the current decibel level and set it as a variable?

Time:12-30

I'm looking to find the current decibel level in a room using a microphone and setting it as a variable. I haven't been able to find any python code on this so I'm very stuck.

It would be good if the variable could refresh every 0.3 of a second but it doesn't have to.

Thanks for your help!!

CodePudding user response:

Here is some python code using the pyaudio library that can calculate the dB level using Root Mean Square (RMS) and print it every 0.3 seconds. Both the rms and db are available as variables.

import pyaudio
import time
from math import log10
import audioop  

p = pyaudio.PyAudio()
WIDTH = 2
RATE = int(p.get_default_input_device_info()['defaultSampleRate'])
DEVICE = p.get_default_input_device_info()['index']
rms = 0
print(p.get_default_input_device_info())

def callback(in_data, frame_count, time_info, status):
    global rms
    rms = audioop.rms(in_data, WIDTH) / 32767
    return in_data, pyaudio.paContinue


stream = p.open(format=p.get_format_from_width(WIDTH),
                input_device_index=DEVICE,
                channels=1,
                rate=RATE,
                input=True,
                output=False,
                stream_callback=callback)

stream.start_stream()

while stream.is_active(): 
    db = 20 * log10(rms)
    print(f"RMS: {rms} DB: {db}") 
    # refresh every 0.3 seconds 
    time.sleep(0.3)

stream.stop_stream()
stream.close()

p.terminate()

Note

As mentioned in the comment above - measuring dB can be a deeper topic than perhaps you require here. Without some info about the usecase, just note that although the method here is the most common you'll likely see - it only compares peaks to itself. This question has a great discussion about this.

If you need a real world measurement of decibels, you'll need reference measurements, calibrated equipment and a little more research!

  • Related