Skip to content

SoundDeviceSink

Base classes

Name Children Inherits
AudioSink
anyvoice.base
Abstract base class for audio output backends.

⋔ Inheritance diagram

graph TD
  3330750070["sinks.SoundDeviceSink"]
  3407701203["base.AudioSink"]
  925645236["abc.ABC"]
  2751680898["builtins.object"]
  3407701203 --> 3330750070
  925645236 --> 3407701203
  2751680898 --> 925645236

🛈 DocStrings

Bases: AudioSink

Audio sink that plays PCM audio through the system speakers.

Uses sounddevice for real-time audio playback.

Parameters:

Name Type Description Default
sample_rate int

Audio sample rate in Hz. Defaults to 24000.

24000
channels int

Number of audio channels. Defaults to 1 (mono).

1
Source code in src/anyvoice/sinks.py
class SoundDeviceSink(AudioSink):
    """Audio sink that plays PCM audio through the system speakers.

    Uses sounddevice for real-time audio playback.

    Args:
        sample_rate: Audio sample rate in Hz. Defaults to 24000.
        channels: Number of audio channels. Defaults to 1 (mono).
    """

    def __init__(
        self,
        *,
        sample_rate: int = 24000,
        channels: int = 1,
    ) -> None:
        self._sample_rate = sample_rate
        self._channels = channels
        self._stream: Any = None

    async def __aenter__(self) -> Self:
        """Start the audio output stream."""
        import sounddevice as sd  # type: ignore[import-untyped]

        self._stream = sd.RawOutputStream(
            samplerate=self._sample_rate,
            channels=self._channels,
            dtype="int16",
        )
        self._stream.start()
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Stop and close the audio output stream."""
        if (stream := self._stream) is not None:
            self._stream = None
            # stop() waits for the pending buffers to play: keep the loop free
            await asyncio.to_thread(stream.stop)
            await asyncio.to_thread(stream.close)

    async def write(self, chunk: bytes) -> None:
        """Write audio chunk to the output stream.

        Args:
            chunk: PCM audio data to play.
        """
        if self._stream is not None and chunk:
            # Run blocking write in executor to not block async loop
            loop = asyncio.get_running_loop()
            await loop.run_in_executor(None, self._stream.write, chunk)

__aenter__ async

__aenter__() -> Self

Start the audio output stream.

Source code in src/anyvoice/sinks.py
async def __aenter__(self) -> Self:
    """Start the audio output stream."""
    import sounddevice as sd  # type: ignore[import-untyped]

    self._stream = sd.RawOutputStream(
        samplerate=self._sample_rate,
        channels=self._channels,
        dtype="int16",
    )
    self._stream.start()
    return self

__aexit__ async

__aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Stop and close the audio output stream.

Source code in src/anyvoice/sinks.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Stop and close the audio output stream."""
    if (stream := self._stream) is not None:
        self._stream = None
        # stop() waits for the pending buffers to play: keep the loop free
        await asyncio.to_thread(stream.stop)
        await asyncio.to_thread(stream.close)

write async

write(chunk: bytes) -> None

Write audio chunk to the output stream.

Parameters:

Name Type Description Default
chunk bytes

PCM audio data to play.

required
Source code in src/anyvoice/sinks.py
async def write(self, chunk: bytes) -> None:
    """Write audio chunk to the output stream.

    Args:
        chunk: PCM audio data to play.
    """
    if self._stream is not None and chunk:
        # Run blocking write in executor to not block async loop
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(None, self._stream.write, chunk)

:fa-brands-github: Show source on GitHub