diff --git a/bot.py b/bot.py index 6d9576b..5be70d8 100644 --- a/bot.py +++ b/bot.py @@ -95,13 +95,11 @@ class Bot(commands.Bot): voice_connection = await channel.connect() # Create an audio stream from selected device - self.streamHandler = sound.PCMStream(self.DEVICE_ID) + self.streamHandler = sound.PCMStream(self.DEVICE_ID, voice_connection) + # Start the audio stream await self.streamHandler.play() - # Play the stream - voice_connection.play(discord.PCMAudio(self.streamHandler)) - # Start the SDR and begin playing to the audio stream self.start_sdr() diff --git a/sound.py b/sound.py index c33d97e..cd6d46e 100644 --- a/sound.py +++ b/sound.py @@ -1,5 +1,7 @@ +import threading import time - +import audioop +import discord import sounddevice import sounddevice as sd from pprint import pformat @@ -13,14 +15,18 @@ sd.default.samplerate = 48000 class PCMStream: globals() - def __init__(self, _device_id): + def __init__(self, _device_id, _voice_connection): self.stream = sd.RawInputStream(device=_device_id) + self.NoiseGate = NoiseGate(_voice_connection, self) def change_device(self, _device_id): self.clean_up() self.stream = sd.RawInputStream(device=_device_id) + async def connect(self): + self.NoiseGate.start() + # Stops and destroys the current stream def clean_up(self): if not self.stream.closed: @@ -43,11 +49,27 @@ class PCMStream: # frame is 4 bytes frames = int(num_bytes / 4) data = self.stream.read(frames)[0] - # convert to pcm format return bytes(data) +class NoiseGate(threading.Thread): + def __init__(self, _voice_connection, _pcmstream_instance): + super().__init__() + self.voice_connection = _voice_connection + self.PCMStream_Instance = _pcmstream_instance + + def run(self) -> None: + while self.voice_connection.is_connected(): + if float(20 * audioop.rms(self.PCMStream_Instance.read(16), 2)) >= 5: + # Play the stream + self.voice_connection.play(discord.PCMAudio(self.PCMStream_Instance)) + while float(20 * audioop.rms(self.PCMStream_Instance.read(16), 2)) >= 5: + time.sleep(.5) + self.voice_connection.stop() + time.sleep(.1) + + class DeviceNotFoundError(Exception): def __init__(self): self.devices = sd.query_devices() @@ -73,4 +95,8 @@ def query_devices(): if not options: raise DeviceNotFoundError() - return options \ No newline at end of file + return options + + + +