Files
Discord-Radio-Bot/NoiseGate.py
2022-02-12 19:59:38 -05:00

68 lines
2.1 KiB
Python

import threading
import time
import numpy as np
import discord
import sounddevice as sd
from threading import Thread, Event
noise_gate_trigger = 0 # Set this value for the trigger on the noise-gate
voice_connection = None
audio_stream = None
last_callback_value = 0
class NoiseGate(Thread):
def __init__(self, trigger_value: int = 700):
global noise_gate_trigger
super(NoiseGate, self).__init__()
self.stream = None
self.stop_NG = threading.Event()
self.NG_Started = threading.Event()
noise_gate_trigger = trigger_value
def init_stream(self, num, _voice_connection, _audio_stream):
global voice_connection, audio_stream
self.stream = sd.InputStream(device=num, callback=stream_callback)
voice_connection = _voice_connection
audio_stream = _audio_stream
def run(self) -> None:
self.NG_Started.set()
self.stream.start()
while not self.stop_NG.is_set():
#print("Main loop start")
if last_callback_value >= noise_gate_trigger:
trigger_noise_gate(True)
while last_callback_value >= noise_gate_trigger:
time.sleep(6)
trigger_noise_gate(False)
#print("Main loop end")
self.stream.stop()
self.stream.close()
self.NG_Started.clear()
voice_connection.stop()
print('Thread #%s stopped' % self.ident)
def stream_callback(indata, *args):
global last_callback_value
volume_normalization = np.linalg.norm(indata) * 10
last_callback_value = int(volume_normalization)
#print(f"Callback Value: {last_callback_value}")
def trigger_noise_gate(triggered: bool):
if triggered:
if not voice_connection.is_playing():
voice_connection.play(discord.PCMAudio(audio_stream))
# print("|" * int(volume_normalization / 4))
print("Noise Gate was Triggered")
#time.sleep(10)
else:
if voice_connection.is_playing():
print("Noise Gate stopped")
voice_connection.pause()
# try disconnecting and reconnecting