Added noisegate to the 'sound' file and integrated it with its function

This commit is contained in:
Logan Cusano
2022-03-26 01:35:02 -04:00
parent 12aa4d6f51
commit 465c0e00ea
2 changed files with 32 additions and 8 deletions

6
bot.py
View File

@@ -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()

View File

@@ -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
return options