Compare commits
11 Commits
master
...
Noisegate_
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b528f2509c | ||
|
|
aba87e4072 | ||
|
|
361f88dc4e | ||
|
|
51ffb00dd6 | ||
|
|
bc618982e9 | ||
|
|
b01ec700f7 | ||
|
|
cd69fa69ed | ||
|
|
3d73da72d6 | ||
|
|
663735210c | ||
|
|
4371b02ab6 | ||
|
|
80f83f2026 |
@@ -3,7 +3,7 @@ import logging
|
||||
import os
|
||||
from datetime import date
|
||||
from os.path import exists
|
||||
from NoiseGatev2 import AudioStream
|
||||
from NoiseGatev2 import AudioStream, query_devices
|
||||
|
||||
# Handler configs
|
||||
PDB_ACCEPTABLE_HANDLERS = {'gqrx': {
|
||||
@@ -53,20 +53,24 @@ def read_config_file():
|
||||
config = configparser.ConfigParser()
|
||||
config.read('./config.ini')
|
||||
|
||||
config_return = {
|
||||
'Bot Token': config['Bot_Info']['Token'],
|
||||
'Device ID': int(config['Device']['ID']),
|
||||
'Device Name': str(config['Device']['Name']),
|
||||
'Mention Group': str(config['Bot_Info']['Mention_Group']),
|
||||
'Channel ID': int(config['Bot_Info']['Channel_ID']),
|
||||
'Handler': str(config['Config']['Handler'])
|
||||
}
|
||||
try:
|
||||
config_return = {
|
||||
'Bot Token': config['Bot_Info']['Token'],
|
||||
'Device ID': int(config['Device']['ID']),
|
||||
'Device Name': str(config['Device']['Name']),
|
||||
'Mention Group': str(config['Bot_Info']['Mention_Group']),
|
||||
'Channel ID': int(config['Bot_Info']['Channel_ID']),
|
||||
'Handler': str(config['Config']['Handler'])
|
||||
}
|
||||
|
||||
LOGGER.debug("Found config options:")
|
||||
for key in config_return.keys():
|
||||
LOGGER.debug(f"\t{key} : {config_return[key]}")
|
||||
LOGGER.debug("Found config options:")
|
||||
for key in config_return.keys():
|
||||
LOGGER.debug(f"\t{key} : {config_return[key]}")
|
||||
|
||||
return config_return
|
||||
return config_return
|
||||
except Exception as err:
|
||||
LOGGER.warning(err)
|
||||
return None
|
||||
|
||||
|
||||
def write_config_file(**kwargs):
|
||||
@@ -121,7 +125,8 @@ def write_config_file(**kwargs):
|
||||
|
||||
|
||||
def get_device_list():
|
||||
list_of_devices = AudioStream().list_devices()
|
||||
list_of_devices = query_devices().items()
|
||||
LOGGER.info("Returning queried device list:")
|
||||
LOGGER.debug(list_of_devices)
|
||||
return list_of_devices
|
||||
|
||||
|
||||
131
NoiseGatev2.py
131
NoiseGatev2.py
@@ -2,109 +2,58 @@ import audioop
|
||||
import logging
|
||||
import math
|
||||
import time
|
||||
|
||||
import sounddevice
|
||||
import pyaudio
|
||||
import discord
|
||||
import numpy
|
||||
from pprint import pformat
|
||||
|
||||
voice_connection = None
|
||||
|
||||
LOGGER = logging.getLogger("Discord_Radio_Bot.NoiseGateV2")
|
||||
DEFAULT = 0
|
||||
|
||||
|
||||
# noinspection PyUnresolvedReferences
|
||||
class AudioStream:
|
||||
def __init__(self, _channels: int = 2, _sample_rate: int = 48000, _frames_per_buffer: int = 1024,
|
||||
_input_device_index: int = None, _output_device_index: int = None, _input: bool = True,
|
||||
_output: bool = True, _init_on_startup: bool = True):
|
||||
self.paInstance_kwargs = {
|
||||
'format': pyaudio.paInt16,
|
||||
_device_index: int = None, _init_on_startup: bool = True):
|
||||
self.sd_kwargs = {
|
||||
'dtype': 'int16',
|
||||
'channels': _channels,
|
||||
'rate': _sample_rate,
|
||||
'input': _input,
|
||||
'output': _output,
|
||||
'frames_per_buffer': _frames_per_buffer
|
||||
'samplerate': _sample_rate,
|
||||
'blocksize': _frames_per_buffer
|
||||
}
|
||||
|
||||
if _input_device_index:
|
||||
if _input:
|
||||
self.paInstance_kwargs['input_device_index'] = _input_device_index
|
||||
else:
|
||||
LOGGER.warning(f"[AudioStream.__init__]:\tInput was not enabled."
|
||||
f" Reinitialize with '_input=True'")
|
||||
if _device_index:
|
||||
self.sd_kwargs['device'] = _device_index
|
||||
|
||||
if _output_device_index:
|
||||
if _output:
|
||||
self.paInstance_kwargs['output_device_index'] = _output_device_index
|
||||
else:
|
||||
LOGGER.warning(f"[AudioStream.__init__]:\tOutput was not enabled."
|
||||
f" Reinitialize with '_output=True'")
|
||||
# Define and initialize stream object if we have been passed a device ID (pyaudio.open)
|
||||
self.stream = None
|
||||
|
||||
if _init_on_startup:
|
||||
# Init PyAudio instance
|
||||
LOGGER.info("Creating PyAudio instance")
|
||||
self.paInstance = pyaudio.PyAudio()
|
||||
|
||||
# Define and initialize stream object if we have been passed a device ID (pyaudio.open)
|
||||
self.stream = None
|
||||
|
||||
if _output_device_index or _input_device_index:
|
||||
if _device_index:
|
||||
if _init_on_startup:
|
||||
LOGGER.info("Init stream")
|
||||
self.init_stream()
|
||||
|
||||
def init_stream(self, _new_output_device_index: int = None, _new_input_device_index: int = None):
|
||||
def init_stream(self, _new_device_index: int = None):
|
||||
# Check what device was asked to be changed (or set)
|
||||
if _new_input_device_index:
|
||||
if self.paInstance_kwargs['input']:
|
||||
self.paInstance_kwargs['input_device_index'] = _new_input_device_index
|
||||
else:
|
||||
LOGGER.warning(f"[AudioStream.init_stream]:\tInput was not enabled when initialized."
|
||||
f" Reinitialize with '_input=True'")
|
||||
|
||||
if _new_output_device_index:
|
||||
if self.paInstance_kwargs['output']:
|
||||
self.paInstance_kwargs['output_device_index'] = _new_output_device_index
|
||||
else:
|
||||
LOGGER.warning(f"[AudioStream.init_stream]:\tOutput was not enabled when initialized."
|
||||
f" Reinitialize with '_output=True'")
|
||||
if _new_device_index:
|
||||
self.sd_kwargs['device'] = _new_input_device_index
|
||||
|
||||
self.close_if_open()
|
||||
|
||||
# Open the stream
|
||||
self.stream = self.paInstance.open(**self.paInstance_kwargs)
|
||||
self.stream = sounddevice.RawStream(**self.sd_kwargs)
|
||||
|
||||
def close_if_open(self):
|
||||
# Stop the stream if it is started
|
||||
if self.stream:
|
||||
if self.stream.is_active():
|
||||
self.stream.stop_stream()
|
||||
if self.stream.active:
|
||||
self.stream.stop()
|
||||
self.stream.close()
|
||||
LOGGER.debug(f"[ReopenStream.close_if_open]:\t Stream was open; It was closed.")
|
||||
|
||||
def list_devices(self, _display_input_devices: bool = True, _display_output_devices: bool = True):
|
||||
info = self.paInstance.get_host_api_info_by_index(0)
|
||||
numdevices = info.get('deviceCount')
|
||||
|
||||
devices = {
|
||||
'Input': {},
|
||||
'Output': {}
|
||||
}
|
||||
for i in range(0, numdevices):
|
||||
if (self.paInstance.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
|
||||
input_device = self.paInstance.get_device_info_by_host_api_device_index(0, i).get('name')
|
||||
devices['Input'][i] = input_device
|
||||
if _display_input_devices:
|
||||
LOGGER.debug("Input Device id ", i, " - ", input_device)
|
||||
|
||||
if (self.paInstance.get_device_info_by_host_api_device_index(0, i).get('maxOutputChannels')) > 0:
|
||||
output_device = self.paInstance.get_device_info_by_host_api_device_index(0, i).get('name')
|
||||
devices['Output'][i] = output_device
|
||||
if _display_output_devices:
|
||||
LOGGER.debug("Output Device id ", i, " - ", output_device)
|
||||
|
||||
return devices
|
||||
|
||||
async def stop(self):
|
||||
await voice_connection.disconnect()
|
||||
self.close_if_open()
|
||||
@@ -126,12 +75,13 @@ class NoiseGate(AudioStream):
|
||||
global voice_connection
|
||||
# Start the audio stream
|
||||
LOGGER.debug(f"Starting stream")
|
||||
self.stream.start_stream()
|
||||
self.stream.start()
|
||||
# Start the stream to discord
|
||||
self.core()
|
||||
|
||||
def core(self, error=None):
|
||||
if error:
|
||||
LOGGER.info('Error in the core')
|
||||
LOGGER.warning(error)
|
||||
|
||||
while not voice_connection.is_connected():
|
||||
@@ -139,13 +89,16 @@ class NoiseGate(AudioStream):
|
||||
|
||||
if not voice_connection.is_playing():
|
||||
LOGGER.debug(f"Playing stream to discord")
|
||||
voice_connection.play(self.NGStream, after=self.core)
|
||||
voice_connection.play(discord.PCMAudio(self.NGStream), after=self.core)
|
||||
|
||||
def list_devices(self):
|
||||
return query_devices()
|
||||
|
||||
async def close(self):
|
||||
LOGGER.debug(f"Closing")
|
||||
await voice_connection.disconnect()
|
||||
if self.stream.is_active:
|
||||
self.stream.stop_stream()
|
||||
if self.stream.active:
|
||||
self.stream.stop()
|
||||
LOGGER.debug(f"Stopping stream")
|
||||
|
||||
|
||||
@@ -158,10 +111,11 @@ class NoiseGateStream(discord.AudioSource):
|
||||
self.NG_fadeout_count = 0 # A count set when the noisegate is triggered and was de-triggered
|
||||
self.process_set_count = 0 # Counts how many processes have been made
|
||||
|
||||
def read(self):
|
||||
def read(self, num_bytes):
|
||||
num_frames = num_bytes / 4
|
||||
try:
|
||||
while voice_connection.is_connected():
|
||||
curr_buffer = bytearray(self.stream.stream.read(960))
|
||||
curr_buffer = bytearray(self.stream.stream.read(num_frames))
|
||||
buffer_rms = audioop.rms(curr_buffer, 2)
|
||||
if buffer_rms > 0:
|
||||
buffer_decibel = 20 * math.log10(buffer_rms)
|
||||
@@ -202,6 +156,31 @@ class NoiseGateStream(discord.AudioSource):
|
||||
datalist[i] = chunk.astype(numpy.int16)
|
||||
|
||||
|
||||
class DeviceNotFoundError(Exception):
|
||||
def __init__(self):
|
||||
self.devices = sounddevice.query_devices()
|
||||
self.host_apis = sounddevice.query_hostapis()
|
||||
super().__init__("No Devices Found")
|
||||
def __str__(self):
|
||||
return (
|
||||
f"Devices \n"
|
||||
f"{self.devices} \n "
|
||||
f"Host APIs \n"
|
||||
f"{pformat(self.host_apis)}"
|
||||
)
|
||||
|
||||
|
||||
def query_devices():
|
||||
options = {
|
||||
device.get("name"): index
|
||||
for index, device in enumerate(sounddevice.query_devices())
|
||||
if (device.get("max_input_channels") > 0 and device.get("hostapi") == DEFAULT)
|
||||
}
|
||||
if not options:
|
||||
raise DeviceNotFoundError()
|
||||
return options
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
input_index = int(input("Input:\t"))
|
||||
|
||||
19
bot.py
19
bot.py
@@ -14,9 +14,11 @@ class Bot(commands.Bot):
|
||||
def __init__(self, **kwargs):
|
||||
# If there is no custom command prefix (!help, ?help, etc.), use '>!' but also accept @ mentions
|
||||
if 'command_prefix' not in kwargs.keys():
|
||||
bot_intents = set_server_intents()
|
||||
kwargs['command_prefix'] = '>!'
|
||||
commands.Bot.__init__(self, command_prefix=commands.when_mentioned_or(kwargs['command_prefix']),
|
||||
activity=discord.Game(name=f"@ me"), status=discord.Status.idle)
|
||||
activity=discord.Game(name=f"@ me"), status=discord.Status.idle,
|
||||
intents=bot_intents)
|
||||
|
||||
# Create the logger for the bot
|
||||
self.logger = logging.getLogger("Discord_Radio_Bot.Bot")
|
||||
@@ -37,9 +39,7 @@ class Bot(commands.Bot):
|
||||
self.Bot_Connected = False
|
||||
|
||||
# Init the audio devices list
|
||||
#self.Devices_List = sound.query_devices().items()
|
||||
self.Devices_List = NoiseGatev2.AudioStream().list_devices(_display_input_devices=False,
|
||||
_display_output_devices=False)
|
||||
self.Devices_List = NoiseGatev2.query_devices().items()
|
||||
|
||||
# Init radio parameters
|
||||
self.profile_name = BotResources.DEFAULT_RADIO_SETTINGS['profile_name']
|
||||
@@ -106,7 +106,7 @@ class Bot(commands.Bot):
|
||||
|
||||
# Create an audio stream from selected device
|
||||
self.logger.debug("Starting noisegate/stream handler")
|
||||
self.streamHandler = NoiseGatev2.NoiseGate(_input_device_index=self.DEVICE_ID,
|
||||
self.streamHandler = NoiseGatev2.NoiseGate(_device_index=self.DEVICE_ID,
|
||||
_voice_connection=voice_connection,
|
||||
_noise_gate_threshold=self.noisegate_sensitivity)
|
||||
# Start the audio stream
|
||||
@@ -580,3 +580,12 @@ class Bot(commands.Bot):
|
||||
message_body += f"\tSquelch:\t\t\t\t{config[section]['Squelch']}\n"
|
||||
|
||||
return message_body
|
||||
|
||||
|
||||
# Set discord intents and return the intent object
|
||||
def set_server_intents():
|
||||
bot_intents = discord.Intents.default()
|
||||
#bot_intents.messages = True
|
||||
#bot_intents.message_content = True
|
||||
#bot_intents.members = True
|
||||
return bot_intents
|
||||
5
main.py
5
main.py
@@ -39,6 +39,11 @@ def main(**passed_config):
|
||||
|
||||
config = BotResources.read_config_file()
|
||||
|
||||
if not config:
|
||||
LOGGER.warning("No config file exists, please enter this information now")
|
||||
BotResources.write_config_file(init=True)
|
||||
config = BotResources.read_config_file()
|
||||
|
||||
# Overwrite config options if they were passed
|
||||
if len(passed_config.keys()) == 0:
|
||||
for sub in config:
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
discord~=1.7.3
|
||||
numpy==1.22.3
|
||||
scipy==1.8.0
|
||||
matplotlib~=3.5.1
|
||||
pyrtlsdr~=0.2.92
|
||||
PyAudio~=0.2.11
|
||||
discord==2.1.0
|
||||
numpy==1.23.5
|
||||
PyAudio==0.2.12
|
||||
sounddevice==0.4.5
|
||||
|
||||
Reference in New Issue
Block a user