Skip to content

Commit

Permalink
Add silence padding after transmission breaks
Browse files Browse the repository at this point in the history
Prevents unwanted interpolation/distortion of audio by sending silence
packets after pausing or ending the audio stream.
  • Loading branch information
imayhaveborkedit committed Sep 22, 2023
1 parent 3f92f35 commit 48b4ea8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
2 changes: 2 additions & 0 deletions discord/opus.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ class SignalCtl(TypedDict):

_log = logging.getLogger(__name__)

OPUS_SILENCE = b'\xF8\xFF\xFE'

c_int_ptr = ctypes.POINTER(ctypes.c_int)
c_int16_ptr = ctypes.POINTER(ctypes.c_int16)
c_float_ptr = ctypes.POINTER(ctypes.c_float)
Expand Down
13 changes: 12 additions & 1 deletion discord/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@

from .enums import SpeakingState
from .errors import ClientException
from .opus import Encoder as OpusEncoder
from .opus import Encoder as OpusEncoder, OPUS_SILENCE
from .oggparse import OggStream
from .utils import MISSING

Expand Down Expand Up @@ -720,6 +720,7 @@ def _do_run(self) -> None:
while not self._end.is_set():
# are we paused?
if not self._resumed.is_set():
self.send_silence()
# wait until we aren't
self._resumed.wait()
continue
Expand All @@ -744,6 +745,8 @@ def _do_run(self) -> None:
delay = max(0, self.DELAY + (next_time - time.perf_counter()))
time.sleep(delay)

self.send_silence()

def run(self) -> None:
try:
self._do_run()
Expand Down Expand Up @@ -800,3 +803,11 @@ def _speak(self, speaking: SpeakingState) -> None:
asyncio.run_coroutine_threadsafe(self.client.ws.speak(speaking), self.client.client.loop)
except Exception:
_log.exception("Speaking call in player failed")

def send_silence(self, count: int = 5) -> None:
try:
for n in range(count):
self.client.send_audio_packet(OPUS_SILENCE, encode=False)
except Exception:
# Any possible error (probably a socket error) is so inconsequential it's not even worth logging
pass

0 comments on commit 48b4ea8

Please sign in to comment.