stream blank when no sound

This commit is contained in:
Logan Cusano
2025-07-14 21:17:09 -04:00
parent a634ea2260
commit abd78c83d2

View File

@@ -6,12 +6,18 @@ from internal.logger import create_logger
LOGGER = create_logger(__name__) LOGGER = create_logger(__name__)
# The size of a 20ms, 48kHz, stereo, 16-bit PCM audio frame.
# (960 frames * 2 channels * 2 bytes/sample)
DISCORD_FRAME_SIZE = 3840
SILENT_FRAME = b'\x00' * DISCORD_FRAME_SIZE
# noinspection PyUnresolvedReferences # noinspection PyUnresolvedReferences
class AudioStream: class AudioStream:
def __init__(self, _channels: int = 2, _sample_rate: int = 48000, _frames_per_buffer: int = 960, def __init__(self, _channels: int = 2, _sample_rate: int = 48000, _frames_per_buffer: int = 960,
_input_device_index: int = None, _output_device_index: int = None, _input: bool = True, _input_device_index: int = None, _output_device_index: int = None, _input: bool = True,
_output: bool = True, _init_on_startup: bool = True): _output: bool = True, _init_on_startup: bool = True):
# NOTE: frames_per_buffer changed to 960 to match Discord's 20ms frame size # Corrected frames_per_buffer to 960 to match Discord's 20ms frame size
self.paInstance_kwargs = { self.paInstance_kwargs = {
'format': pyaudio.paInt16, 'format': pyaudio.paInt16,
'channels': _channels, 'channels': _channels,
@@ -106,19 +112,18 @@ class NoiseGate(AudioStream):
def core(self, error=None): def core(self, error=None):
if error: if error:
LOGGER.warning(f"Audio stream stopped unexpectedly with error: {error}") LOGGER.warning(f"Audio stream stopped unexpectedly with error: {error}")
return # Avoid recursion on error return
if self.voice_connection.is_connected() and not self.voice_connection.is_playing(): if self.voice_connection.is_connected() and not self.voice_connection.is_playing():
LOGGER.debug("Playing stream to discord") LOGGER.debug("Playing stream to discord")
# The 'after' callback can be prone to loops, simplified here
self.voice_connection.play(self.NGStream, after=lambda e: self.core(e)) self.voice_connection.play(self.NGStream, after=lambda e: self.core(e))
async def close(self): async def close(self):
LOGGER.debug("Closing NoiseGate resources...") LOGGER.debug("Closing NoiseGate resources...")
if self.voice_connection and self.voice_connection.is_connected(): if self.voice_connection and self.voice_connection.is_connected():
self.voice_connection.stop() # Stop sending audio self.voice_connection.stop()
self.close_if_open() # Close PyAudio stream self.close_if_open()
if self.paInstance: if self.paInstance:
self.paInstance.terminate() self.paInstance.terminate()
@@ -130,21 +135,19 @@ class NoiseGateStream(discord.AudioSource):
def __init__(self, noise_gate_instance: NoiseGate): def __init__(self, noise_gate_instance: NoiseGate):
super(NoiseGateStream, self).__init__() super(NoiseGateStream, self).__init__()
self.noise_gate = noise_gate_instance self.noise_gate = noise_gate_instance
self.NG_fadeout = 12 # Equivalent to 240ms of audio frames (240 / 20ms) self.NG_fadeout = 12
self.NG_fadeout_count = 0 self.NG_fadeout_count = 0
self.process_set_count = 0 self.process_set_count = 0
def read(self): def read(self):
try: try:
# Check connection status via the parent NoiseGate instance
if not self.noise_gate.voice_connection.is_connected(): if not self.noise_gate.voice_connection.is_connected():
return b'' return SILENT_FRAME
# Read from the PyAudio stream, also via the parent instance
curr_buffer = self.noise_gate.stream.read(960, exception_on_overflow=False) curr_buffer = self.noise_gate.stream.read(960, exception_on_overflow=False)
if not curr_buffer: if len(curr_buffer) != DISCORD_FRAME_SIZE:
return b'' return SILENT_FRAME
buffer_rms = audioop.rms(curr_buffer, 2) buffer_rms = audioop.rms(curr_buffer, 2)
@@ -165,11 +168,11 @@ class NoiseGateStream(discord.AudioSource):
self.process_set_count += 1 self.process_set_count += 1
return bytes(curr_buffer) return bytes(curr_buffer)
return b'' # Return silence if below threshold and not in fadeout return SILENT_FRAME
except IOError as e: except IOError as e:
LOGGER.error(f"PyAudio IOError in read(): {e}") LOGGER.error(f"PyAudio IOError in read(): {e}")
return b'' # Return silence to not break the Discord audio pump return SILENT_FRAME
except Exception as e: except Exception as e:
LOGGER.error(f"Unhandled exception in NoiseGateStream.read: {e}", exc_info=True) LOGGER.error(f"Unhandled exception in NoiseGateStream.read: {e}", exc_info=True)
return b'' return SILENT_FRAME