Last active
January 23, 2022 06:02
-
-
Save ethanjurman/8999b1f12baa56b68484c1ef06511c8f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pyaudio | |
import numpy as np | |
import time | |
CHUNK = 2048 | |
RATE = 44100 | |
pa = pyaudio.PyAudio() | |
stream = pa.open( | |
format=pyaudio.paInt16, | |
channels=2, | |
rate=RATE, | |
input=True, | |
frames_per_buffer=CHUNK, | |
input_device_index=0 # microphone input, remove this line to use default | |
) | |
# ADJUST THESE THRESHOLDS IF NECESSARY | |
volumeMap = {00:"▁",25:"▂",50:"▃",100:"▅",500:"▆",900:"▇"} | |
MINUTE_BUFFER_SIZE = 120 | |
QUICK_BUFFER_SIZE = 10 | |
VOL_THRESHOLD = 200 | |
quick_buffer = ["▁"] * QUICK_BUFFER_SIZE | |
minute_buffer = ["▁"] * MINUTE_BUFFER_SIZE | |
current_time = int(time.time()) | |
stream.start_stream() | |
def getCurrentVolume(): | |
data = np.abs(np.frombuffer(stream.read(CHUNK), dtype=np.int16)) | |
return np.average(data) | |
def getHighestVolumeFromQuickBuffer(): | |
if "▇" in quick_buffer: | |
return "▇" | |
elif "▆" in quick_buffer: | |
return "▆" | |
elif "▅" in quick_buffer: | |
return "▅" | |
elif "▃" in quick_buffer: | |
return "▃" | |
elif "▂" in quick_buffer: | |
return "▂" | |
return "▁" | |
while(True): | |
# get current volume and based on threshold add it to quick buffer | |
currentVolume = getCurrentVolume() | |
emoji = "▁" | |
for volThreshold in volumeMap: | |
if (currentVolume > volThreshold): | |
emoji = volumeMap[volThreshold] | |
quick_buffer.append(emoji) | |
quick_buffer.pop(0) | |
# if time has incremented one second, add emoji minute buffer | |
if (int(time.time()) != current_time): | |
minute_buffer.append(getHighestVolumeFromQuickBuffer()) | |
current_time = int(time.time()) | |
if len(minute_buffer) > MINUTE_BUFFER_SIZE: | |
minute_buffer.pop(0) | |
# print minute buffer | |
print("|", end="") | |
for item in minute_buffer: | |
print(item, end="") | |
print("|", end="") | |
# print quick buffer | |
for item in quick_buffer: | |
print(item, end="") | |
print("|", end="") | |
# print volume readout | |
print(str(int(currentVolume)).zfill(4), end="") | |
print(" ", end="") | |
# write to same line | |
print("", end="\r") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works with Python3
Requires numpy and pyaudio (install with pip)
Video explanation: https://www.youtube.com/watch?v=OwwfMq5e1tY