-
Notifications
You must be signed in to change notification settings - Fork 1
/
monitor_sound_level.py
38 lines (28 loc) · 1000 Bytes
/
monitor_sound_level.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import pyaudio
import numpy as np
import time
# Set the parameters for audio recording
FORMAT = pyaudio.paInt16
CHANNELS = 1 # Mono audio
RATE = 44100 # Sample rate (Hz)
CHUNK = 1024 # Buffer size
# Create an instance of the PyAudio class
audio = pyaudio.PyAudio()
# Open a stream to capture audio from the USB microphone
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)
# Loop over the audio stream and calculate the sound levels
while True:
# Read audio data from the stream
data = stream.read(CHUNK)
# Convert the audio data to a numpy array
audio_data = np.frombuffer(data, dtype=np.int16)
# Calculate the root mean square (RMS) of the audio data
rms = np.sqrt(np.mean(np.square(audio_data)))
# Print the sound level
if rms > 50:
print(f"Sound level: {rms:.2f}")
time.sleep(.1)
# Close the audio stream and PyAudio instance when done
stream.stop_stream()
stream.close()
audio.terminate()