Skip to content

Instantly share code, notes, and snippets.

@hmahadik
Last active February 16, 2021 15:41
Show Gist options
  • Save hmahadik/02a9f9c646fda6ef75858ae930977d65 to your computer and use it in GitHub Desktop.
Save hmahadik/02a9f9c646fda6ef75858ae930977d65 to your computer and use it in GitHub Desktop.
import pyaudio
import math
import struct
import playsound
CHUNK = 2048
THRESHOLD = 70
REFERENCE_LEVEL = 0.00005
def rms( data ):
count = len(data)/2
format = "%dh"%(count)
shorts = struct.unpack( format, data )
sum_squares = 0.0
for sample in shorts:
n = sample * (1.0/32768)
sum_squares += n*n
return math.sqrt( sum_squares / count )
def decibels(rms):
return 20 * math.log10(rms/REFERENCE_LEVEL)
p = pyaudio.PyAudio()
stream = p.open(format = pyaudio.paInt16,
channels = 1,
rate = 44100,
input = True,
frames_per_buffer = CHUNK)
while True:
data = stream.read(CHUNK)
dB = int(decibels(rms(data)))
print(f"\r {dB} dB [{'*'*(dB)}{' '*(100-dB)}]",end="")
if (dB >= THRESHOLD):
playsound.playsound('alert-1.mp3')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment