Skip to content

anyvoice

Class info

Re-exported classes

Class Module Description
AudioSink anyvoice.base Abstract base class for audio output backends.
CallbackSink anyvoice.sinks Audio sink that passes audio chunks to a user-provided callback.
EdgeTTSProvider anyvoice.providers.edge TTS provider using Microsoft Edge's free TTS service.
FileSink anyvoice.sinks Audio sink that writes PCM audio to a WAV file.
OpenAITTSProvider anyvoice.providers.openai TTS provider using OpenAI's Text-to-Speech API.
SoundDeviceSink anyvoice.sinks Audio sink that plays PCM audio through the system speakers.
TTSProvider anyvoice.base Abstract base class for TTS providers.
TTSSession anyvoice.base Abstract base class for TTS synthesis sessions.
TTSStream anyvoice.stream Orchestrator for streaming TTS with sentence buffering and playback.

🛈 DocStrings

AnyVoice: A streaming-friendly Text-to-Speech library.

This library provides a clean, composable API for TTS synthesis with: - Multiple provider backends (OpenAI, Edge TTS) - Pluggable audio sinks (speakers, file, callback) - Streaming support with sentence buffering - Configurable synchronization modes

Example

from anyvoice import TTSStream, OpenAITTSProvider, SoundDeviceSink

provider = OpenAITTSProvider(api_key="...") session = provider.session(voice="nova")

async with TTSStream(session, sink=SoundDeviceSink()) as tts: await tts.feed("Hello ") await tts.feed("world!")

TTSMode module-attribute

TTSMode = Literal['sync_sentence', 'sync_run', 'async_queue']

TTS synchronization modes.

  • sync_sentence: Wait for each sentence's audio before continuing (slowest, most synchronized)
  • sync_run: Stream fast, wait for all audio at context exit (default)
  • async_queue: Stream fast, synthesis runs in background, context exit does not wait (the rest plays in the background, then session and sink close; wait_closed())

An exception or cancellation inside the context drops pending audio in every mode.

AudioSink

Bases: ABC

Abstract base class for audio output backends.

Audio sinks receive PCM audio chunks and handle output (playback, file writing, etc.).

Usage as context manager

async with SoundDeviceSink() as sink: await sink.write(audio_chunk)

Source code in src/anyvoice/base.py
class AudioSink(ABC):
    """Abstract base class for audio output backends.

    Audio sinks receive PCM audio chunks and handle output
    (playback, file writing, etc.).

    Usage as context manager:
        async with SoundDeviceSink() as sink:
            await sink.write(audio_chunk)
    """

    async def __aenter__(self) -> Self:
        """Enter the sink context, prepare for receiving audio."""
        return self

    async def __aexit__(  # noqa: B027
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Exit the sink context, finalize and cleanup."""

    @abstractmethod
    async def write(self, chunk: bytes) -> None:
        """Write a PCM audio chunk to the sink.

        Args:
            chunk: Raw PCM audio data (16-bit signed, mono).
        """
        ...

__aenter__ async

__aenter__() -> Self

Enter the sink context, prepare for receiving audio.

Source code in src/anyvoice/base.py
async def __aenter__(self) -> Self:
    """Enter the sink context, prepare for receiving audio."""
    return self

__aexit__ async

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

Exit the sink context, finalize and cleanup.

Source code in src/anyvoice/base.py
async def __aexit__(  # noqa: B027
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Exit the sink context, finalize and cleanup."""

write abstractmethod async

write(chunk: bytes) -> None

Write a PCM audio chunk to the sink.

Parameters:

Name Type Description Default
chunk bytes

Raw PCM audio data (16-bit signed, mono).

required
Source code in src/anyvoice/base.py
@abstractmethod
async def write(self, chunk: bytes) -> None:
    """Write a PCM audio chunk to the sink.

    Args:
        chunk: Raw PCM audio data (16-bit signed, mono).
    """
    ...

CallbackSink

Bases: AudioSink

Audio sink that passes audio chunks to a user-provided callback.

Useful for custom audio processing, streaming, or integration with other systems.

Parameters:

Name Type Description Default
callback Callable[[bytes], Awaitable[None]] | Callable[[bytes], None]

Async or sync callable that receives audio chunks.

required
on_close Callable[[], Awaitable[None]] | Callable[[], None] | None

Optional callback invoked when sink closes.

None
Source code in src/anyvoice/sinks.py
class CallbackSink(AudioSink):
    """Audio sink that passes audio chunks to a user-provided callback.

    Useful for custom audio processing, streaming, or integration
    with other systems.

    Args:
        callback: Async or sync callable that receives audio chunks.
        on_close: Optional callback invoked when sink closes.
    """

    def __init__(
        self,
        callback: Callable[[bytes], Awaitable[None]] | Callable[[bytes], None],
        *,
        on_close: Callable[[], Awaitable[None]] | Callable[[], None] | None = None,
    ) -> None:
        self._callback = callback
        self._on_close = on_close

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Invoke close callback if provided."""
        if self._on_close is not None:
            result = self._on_close()
            if asyncio.iscoroutine(result):
                await result

    async def write(self, chunk: bytes) -> None:
        """Pass audio chunk to the callback.

        Args:
            chunk: PCM audio data.
        """
        if chunk:
            result = self._callback(chunk)
            if asyncio.iscoroutine(result):
                await result

__aexit__ async

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

Invoke close callback if provided.

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:
    """Invoke close callback if provided."""
    if self._on_close is not None:
        result = self._on_close()
        if asyncio.iscoroutine(result):
            await result

write async

write(chunk: bytes) -> None

Pass audio chunk to the callback.

Parameters:

Name Type Description Default
chunk bytes

PCM audio data.

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

    Args:
        chunk: PCM audio data.
    """
    if chunk:
        result = self._callback(chunk)
        if asyncio.iscoroutine(result):
            await result

EdgeTTSProvider

Bases: TTSProvider

TTS provider using Microsoft Edge's free TTS service.

Uses edge-tts library to access Microsoft's neural TTS voices. No API key required.

Parameters:

Name Type Description Default
default_voice str

Default voice name. Defaults to "en-US-AriaNeural".

'en-US-AriaNeural'
sample_rate int

Target sample rate for audio output. Defaults to 24000.

24000
Example

provider = EdgeTTSProvider() session = provider.session(voice="en-GB-SoniaNeural", rate="+10%")

async with TTSStream(session, sink=SoundDeviceSink()) as tts: await tts.feed("Hello world!")

Note

Use edge-tts --list-voices to see all available voices. Voice format: {locale}-{Name}Neural (e.g., en-US-AriaNeural)

Source code in src/anyvoice/providers/edge.py
class EdgeTTSProvider(TTSProvider):
    """TTS provider using Microsoft Edge's free TTS service.

    Uses edge-tts library to access Microsoft's neural TTS voices.
    No API key required.

    Args:
        default_voice: Default voice name. Defaults to "en-US-AriaNeural".
        sample_rate: Target sample rate for audio output. Defaults to 24000.

    Example:
        provider = EdgeTTSProvider()
        session = provider.session(voice="en-GB-SoniaNeural", rate="+10%")

        async with TTSStream(session, sink=SoundDeviceSink()) as tts:
            await tts.feed("Hello world!")

    Note:
        Use `edge-tts --list-voices` to see all available voices.
        Voice format: {locale}-{Name}Neural (e.g., en-US-AriaNeural)
    """

    def __init__(
        self,
        *,
        default_voice: str = "en-US-AriaNeural",
        sample_rate: int = 24000,
    ) -> None:
        self._default_voice = default_voice
        self._sample_rate = sample_rate

    async def __aenter__(self) -> Self:
        """Enter provider context (no-op for Edge TTS)."""
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Exit provider context (no-op for Edge TTS)."""

    def session(
        self,
        *,
        voice: str | None = None,
        rate: str = "+0%",
        volume: str = "+0%",
        pitch: str = "+0Hz",
        sample_rate: int | None = None,
        **_: Any,
    ) -> EdgeTTSSession:
        """Create a new Edge TTS session.

        Args:
            voice: Voice name. Defaults to provider's default voice.
            rate: Speaking rate adjustment (e.g., "+25%", "-10%").
            volume: Volume adjustment (e.g., "+10%", "-20%").
            pitch: Pitch adjustment in Hz (e.g., "+10Hz", "-5Hz").
            sample_rate: Target sample rate. Defaults to provider's sample rate.

        Returns:
            Configured Edge TTS session.
        """
        return EdgeTTSSession(
            voice=voice or self._default_voice,
            rate=rate,
            volume=volume,
            pitch=pitch,
            sample_rate=sample_rate or self._sample_rate,
        )

__aenter__ async

__aenter__() -> Self

Enter provider context (no-op for Edge TTS).

Source code in src/anyvoice/providers/edge.py
async def __aenter__(self) -> Self:
    """Enter provider context (no-op for Edge TTS)."""
    return self

__aexit__ async

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

Exit provider context (no-op for Edge TTS).

Source code in src/anyvoice/providers/edge.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Exit provider context (no-op for Edge TTS)."""

session

session(
    *,
    voice: str | None = None,
    rate: str = "+0%",
    volume: str = "+0%",
    pitch: str = "+0Hz",
    sample_rate: int | None = None,
    **_: Any,
) -> EdgeTTSSession

Create a new Edge TTS session.

Parameters:

Name Type Description Default
voice str | None

Voice name. Defaults to provider's default voice.

None
rate str

Speaking rate adjustment (e.g., "+25%", "-10%").

'+0%'
volume str

Volume adjustment (e.g., "+10%", "-20%").

'+0%'
pitch str

Pitch adjustment in Hz (e.g., "+10Hz", "-5Hz").

'+0Hz'
sample_rate int | None

Target sample rate. Defaults to provider's sample rate.

None

Returns:

Type Description
EdgeTTSSession

Configured Edge TTS session.

Source code in src/anyvoice/providers/edge.py
def session(
    self,
    *,
    voice: str | None = None,
    rate: str = "+0%",
    volume: str = "+0%",
    pitch: str = "+0Hz",
    sample_rate: int | None = None,
    **_: Any,
) -> EdgeTTSSession:
    """Create a new Edge TTS session.

    Args:
        voice: Voice name. Defaults to provider's default voice.
        rate: Speaking rate adjustment (e.g., "+25%", "-10%").
        volume: Volume adjustment (e.g., "+10%", "-20%").
        pitch: Pitch adjustment in Hz (e.g., "+10Hz", "-5Hz").
        sample_rate: Target sample rate. Defaults to provider's sample rate.

    Returns:
        Configured Edge TTS session.
    """
    return EdgeTTSSession(
        voice=voice or self._default_voice,
        rate=rate,
        volume=volume,
        pitch=pitch,
        sample_rate=sample_rate or self._sample_rate,
    )

FileSink

Bases: AudioSink

Audio sink that writes PCM audio to a WAV file.

Parameters:

Name Type Description Default
path str | PathLike[str]

Path to the output WAV file.

required
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 FileSink(AudioSink):
    """Audio sink that writes PCM audio to a WAV file.

    Args:
        path: Path to the output WAV file.
        sample_rate: Audio sample rate in Hz. Defaults to 24000.
        channels: Number of audio channels. Defaults to 1 (mono).
    """

    def __init__(
        self,
        path: str | os.PathLike[str],
        *,
        sample_rate: int = 24000,
        channels: int = 1,
    ) -> None:
        self._path = path
        self._sample_rate = sample_rate
        self._channels = channels
        self._chunks: list[bytes] = []

    async def __aenter__(self) -> Self:
        """Prepare for receiving audio."""
        self._chunks = []
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Write collected audio to WAV file."""
        import wave

        if not self._chunks:
            return

        audio_data = b"".join(self._chunks)

        with wave.open(str(self._path), "wb") as wf:
            wf.setnchannels(self._channels)
            wf.setsampwidth(2)  # 16-bit = 2 bytes
            wf.setframerate(self._sample_rate)
            wf.writeframes(audio_data)

        self._chunks = []

    async def write(self, chunk: bytes) -> None:
        """Buffer audio chunk for later writing.

        Args:
            chunk: PCM audio data to save.
        """
        if chunk:
            self._chunks.append(chunk)

__aenter__ async

__aenter__() -> Self

Prepare for receiving audio.

Source code in src/anyvoice/sinks.py
async def __aenter__(self) -> Self:
    """Prepare for receiving audio."""
    self._chunks = []
    return self

__aexit__ async

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

Write collected audio to WAV file.

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:
    """Write collected audio to WAV file."""
    import wave

    if not self._chunks:
        return

    audio_data = b"".join(self._chunks)

    with wave.open(str(self._path), "wb") as wf:
        wf.setnchannels(self._channels)
        wf.setsampwidth(2)  # 16-bit = 2 bytes
        wf.setframerate(self._sample_rate)
        wf.writeframes(audio_data)

    self._chunks = []

write async

write(chunk: bytes) -> None

Buffer audio chunk for later writing.

Parameters:

Name Type Description Default
chunk bytes

PCM audio data to save.

required
Source code in src/anyvoice/sinks.py
async def write(self, chunk: bytes) -> None:
    """Buffer audio chunk for later writing.

    Args:
        chunk: PCM audio data to save.
    """
    if chunk:
        self._chunks.append(chunk)

OpenAITTSProvider

Bases: TTSProvider

TTS provider using OpenAI's Text-to-Speech API.

Provides high-quality neural TTS with streaming support. Requires an OpenAI API key.

Parameters:

Name Type Description Default
api_key str | None

OpenAI API key. If not provided, uses OPENAI_API_KEY env var.

None
base_url str | None

Optional custom API base URL.

None
Example

provider = OpenAITTSProvider(api_key="sk-...") session = provider.session(voice="nova", speed=1.0)

async with TTSStream(session, sink=SoundDeviceSink()) as tts: await tts.feed("Hello world!")

Source code in src/anyvoice/providers/openai.py
class OpenAITTSProvider(TTSProvider):
    """TTS provider using OpenAI's Text-to-Speech API.

    Provides high-quality neural TTS with streaming support.
    Requires an OpenAI API key.

    Args:
        api_key: OpenAI API key. If not provided, uses OPENAI_API_KEY env var.
        base_url: Optional custom API base URL.

    Example:
        provider = OpenAITTSProvider(api_key="sk-...")
        session = provider.session(voice="nova", speed=1.0)

        async with TTSStream(session, sink=SoundDeviceSink()) as tts:
            await tts.feed("Hello world!")
    """

    def __init__(
        self,
        *,
        api_key: str | None = None,
        base_url: str | None = None,
    ) -> None:
        self._api_key = api_key
        self._base_url = base_url
        self._client: AsyncOpenAI | None = None

    async def __aenter__(self) -> Self:
        """Initialize the OpenAI client shared by the sessions created inside."""
        if self._client is None:
            self._client = self._create_client()
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Close the OpenAI client."""
        if self._client is not None:
            await self._client.close()
            self._client = None

    def _create_client(self) -> AsyncOpenAI:
        from openai import AsyncOpenAI

        return AsyncOpenAI(api_key=self._api_key, base_url=self._base_url)

    def session(
        self,
        *,
        model: TTSModel = "tts-1",
        voice: TTSVoice = "alloy",
        speed: float = 1.0,
        chunk_size: int = 1024,
        **_: Any,
    ) -> OpenAITTSSession:
        """Create a new OpenAI TTS session.

        Args:
            model: TTS model ("tts-1" for speed, "tts-1-hd" for quality).
            voice: Voice to use (alloy, echo, fable, onyx, nova, shimmer).
            speed: Speech speed from 0.25 to 4.0. Defaults to 1.0.
            chunk_size: Size of audio chunks in bytes. Defaults to 1024.

        Returns:
            Configured OpenAI TTS session. Inside `async with provider` it uses the
            provider's client; otherwise it creates its own and closes it on exit.
        """
        return OpenAITTSSession(
            self._client,
            model=model,
            voice=voice,
            speed=speed,
            chunk_size=chunk_size,
            client_factory=self._create_client,
        )

__aenter__ async

__aenter__() -> Self

Initialize the OpenAI client shared by the sessions created inside.

Source code in src/anyvoice/providers/openai.py
async def __aenter__(self) -> Self:
    """Initialize the OpenAI client shared by the sessions created inside."""
    if self._client is None:
        self._client = self._create_client()
    return self

__aexit__ async

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

Close the OpenAI client.

Source code in src/anyvoice/providers/openai.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Close the OpenAI client."""
    if self._client is not None:
        await self._client.close()
        self._client = None

session

session(
    *,
    model: TTSModel = "tts-1",
    voice: TTSVoice = "alloy",
    speed: float = 1.0,
    chunk_size: int = 1024,
    **_: Any,
) -> OpenAITTSSession

Create a new OpenAI TTS session.

Parameters:

Name Type Description Default
model TTSModel

TTS model ("tts-1" for speed, "tts-1-hd" for quality).

'tts-1'
voice TTSVoice

Voice to use (alloy, echo, fable, onyx, nova, shimmer).

'alloy'
speed float

Speech speed from 0.25 to 4.0. Defaults to 1.0.

1.0
chunk_size int

Size of audio chunks in bytes. Defaults to 1024.

1024

Returns:

Type Description
OpenAITTSSession

Configured OpenAI TTS session. Inside async with provider it uses the

OpenAITTSSession

provider's client; otherwise it creates its own and closes it on exit.

Source code in src/anyvoice/providers/openai.py
def session(
    self,
    *,
    model: TTSModel = "tts-1",
    voice: TTSVoice = "alloy",
    speed: float = 1.0,
    chunk_size: int = 1024,
    **_: Any,
) -> OpenAITTSSession:
    """Create a new OpenAI TTS session.

    Args:
        model: TTS model ("tts-1" for speed, "tts-1-hd" for quality).
        voice: Voice to use (alloy, echo, fable, onyx, nova, shimmer).
        speed: Speech speed from 0.25 to 4.0. Defaults to 1.0.
        chunk_size: Size of audio chunks in bytes. Defaults to 1024.

    Returns:
        Configured OpenAI TTS session. Inside `async with provider` it uses the
        provider's client; otherwise it creates its own and closes it on exit.
    """
    return OpenAITTSSession(
        self._client,
        model=model,
        voice=voice,
        speed=speed,
        chunk_size=chunk_size,
        client_factory=self._create_client,
    )

SoundDeviceSink

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)

TTSProvider

Bases: ABC

Abstract base class for TTS providers.

Providers hold credentials and client configuration, and act as factories for lightweight sessions.

Usage

provider = OpenAITTSProvider(api_key="...") session = provider.session(voice="nova", speed=1.0)

Source code in src/anyvoice/base.py
class TTSProvider(ABC):
    """Abstract base class for TTS providers.

    Providers hold credentials and client configuration, and act
    as factories for lightweight sessions.

    Usage:
        provider = OpenAITTSProvider(api_key="...")
        session = provider.session(voice="nova", speed=1.0)
    """

    @abstractmethod
    def session(self, **config: Any) -> TTSSession:
        """Create a new synthesis session with the given configuration.

        Args:
            **config: Provider-specific configuration (voice, speed, etc.).

        Returns:
            A new TTSSession configured with the given parameters.
        """
        ...

session abstractmethod

session(**config: Any) -> TTSSession

Create a new synthesis session with the given configuration.

Parameters:

Name Type Description Default
**config Any

Provider-specific configuration (voice, speed, etc.).

{}

Returns:

Type Description
TTSSession

A new TTSSession configured with the given parameters.

Source code in src/anyvoice/base.py
@abstractmethod
def session(self, **config: Any) -> TTSSession:
    """Create a new synthesis session with the given configuration.

    Args:
        **config: Provider-specific configuration (voice, speed, etc.).

    Returns:
        A new TTSSession configured with the given parameters.
    """
    ...

TTSSession

Bases: ABC

Abstract base class for TTS synthesis sessions.

A session represents a single synthesis context with specific configuration (voice, speed, etc.). Sessions are lightweight and created by providers.

Usage

session = provider.session(voice="nova") async for chunk in session.synthesize("Hello world"): await sink.write(chunk)

Source code in src/anyvoice/base.py
class TTSSession(ABC):
    """Abstract base class for TTS synthesis sessions.

    A session represents a single synthesis context with specific
    configuration (voice, speed, etc.). Sessions are lightweight
    and created by providers.

    Usage:
        session = provider.session(voice="nova")
        async for chunk in session.synthesize("Hello world"):
            await sink.write(chunk)
    """

    async def __aenter__(self) -> Self:
        """Enter the session context."""
        return self

    async def __aexit__(  # noqa: B027
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Exit the session context, cleanup resources."""

    @abstractmethod
    def synthesize(self, text: str) -> AsyncIterator[bytes]:
        """Synthesize text to PCM audio.

        Args:
            text: Text to synthesize.

        Yields:
            PCM audio chunks (16-bit signed, mono).
        """
        ...

__aenter__ async

__aenter__() -> Self

Enter the session context.

Source code in src/anyvoice/base.py
async def __aenter__(self) -> Self:
    """Enter the session context."""
    return self

__aexit__ async

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

Exit the session context, cleanup resources.

Source code in src/anyvoice/base.py
async def __aexit__(  # noqa: B027
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Exit the session context, cleanup resources."""

synthesize abstractmethod

synthesize(text: str) -> AsyncIterator[bytes]

Synthesize text to PCM audio.

Parameters:

Name Type Description Default
text str

Text to synthesize.

required

Yields:

Type Description
AsyncIterator[bytes]

PCM audio chunks (16-bit signed, mono).

Source code in src/anyvoice/base.py
@abstractmethod
def synthesize(self, text: str) -> AsyncIterator[bytes]:
    """Synthesize text to PCM audio.

    Args:
        text: Text to synthesize.

    Yields:
        PCM audio chunks (16-bit signed, mono).
    """
    ...

TTSStream

Orchestrator for streaming TTS with sentence buffering and playback.

Coordinates a TTS session with an audio sink, handling: - Text buffering and sentence boundary detection - Synthesis scheduling (sync vs async modes) - Audio playback coordination

Parameters:

Name Type Description Default
session TTSSession

TTS session for synthesis.

required
sink AudioSink | None

Audio sink for output. Defaults to SoundDeviceSink.

None
mode TTSMode

Synchronization mode. Defaults to "sync_run".

'sync_run'
min_text_length int

Minimum characters before synthesizing. Defaults to 20.

20
sentence_terminators frozenset[str] | None

Characters that end sentences.

None
Example

provider = OpenAITTSProvider(api_key="...") session = provider.session(voice="nova")

async with TTSStream(session) as tts: await tts.feed("Hello ") await tts.feed("world! ") await tts.feed("How are you?")

Audio plays and completes before exiting

Source code in src/anyvoice/stream.py
class TTSStream:
    """Orchestrator for streaming TTS with sentence buffering and playback.

    Coordinates a TTS session with an audio sink, handling:
    - Text buffering and sentence boundary detection
    - Synthesis scheduling (sync vs async modes)
    - Audio playback coordination

    Args:
        session: TTS session for synthesis.
        sink: Audio sink for output. Defaults to SoundDeviceSink.
        mode: Synchronization mode. Defaults to "sync_run".
        min_text_length: Minimum characters before synthesizing. Defaults to 20.
        sentence_terminators: Characters that end sentences.

    Example:
        provider = OpenAITTSProvider(api_key="...")
        session = provider.session(voice="nova")

        async with TTSStream(session) as tts:
            await tts.feed("Hello ")
            await tts.feed("world! ")
            await tts.feed("How are you?")
        # Audio plays and completes before exiting
    """

    def __init__(
        self,
        session: TTSSession,
        *,
        sink: AudioSink | None = None,
        mode: TTSMode = "sync_run",
        min_text_length: int = 20,
        sentence_terminators: frozenset[str] | None = None,
    ) -> None:
        self._session = session
        self._sink = sink
        self._mode = mode
        self._min_text_length = min_text_length
        self._sentence_terminators = sentence_terminators or frozenset({".", "!", "?", "\n"})

        # State
        self._text_buffer = ""
        self._sentence_queue: asyncio.Queue[str | None] = asyncio.Queue()
        self._synthesis_task: asyncio.Task[None] | None = None
        self._worker_error: Exception | None = None
        self._exit_stack: contextlib.AsyncExitStack | None = None
        self._closing_task: asyncio.Task[None] | None = None
        self._active = False

    async def __aenter__(self) -> Self:
        """Enter the stream context, prepare session and sink."""
        # Initialize sink (default to SoundDeviceSink if not provided)
        if self._sink is None:
            self._sink = SoundDeviceSink()

        async with contextlib.AsyncExitStack() as stack:
            await stack.enter_async_context(self._session)
            await stack.enter_async_context(self._sink)
            self._exit_stack = stack.pop_all()
        self._active = True
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Exit the stream context, finalize audio and cleanup.

        On an exception (or cancellation) inside the context, pending audio is
        dropped. On a clean exit the remaining text is synthesized; the sync modes
        wait for it, the async modes leave it to a background task which closes
        the session and the sink afterwards (see `wait_closed()`).
        """
        self._active = False
        if exc_type is not None:
            await self._abort_and_close(exc_type, exc_val, exc_tb)
            return
        try:
            await self._flush()
            if self._mode == "async_queue":
                task = asyncio.create_task(self._drain_and_close())
                self._closing_task = task
                _background_tasks.add(task)
                task.add_done_callback(_background_tasks.discard)
                return
            await self._wait_for_completion()
        except BaseException as e:
            await self._abort_and_close(type(e), e, e.__traceback__)
            raise
        await self._close(None, None, None)

    async def wait_closed(self) -> None:
        """Wait until background synthesis finished and session and sink are closed.

        Only does something after the context exit of the async modes (which don't
        wait). Raises the error a background synthesis failed with, if any.
        """
        if self._closing_task is not None:
            await asyncio.shield(self._closing_task)
        self._raise_worker_error()

    async def feed(self, text: str) -> None:
        """Feed text to the TTS stream.

        Text is buffered until sentence boundaries are detected,
        then synthesized according to the configured mode.

        Args:
            text: Text chunk to add to the stream.
        """
        if not self._active:
            msg = "TTSStream must be used as async context manager"
            raise RuntimeError(msg)
        self._raise_worker_error()

        self._text_buffer += text

        # Check for sentence boundaries
        if any(term in self._text_buffer for term in self._sentence_terminators):
            last_term = max(
                (self._text_buffer.rfind(term) for term in self._sentence_terminators),
                default=-1,
            )

            if last_term > 0 and last_term >= self._min_text_length:
                sentence = self._text_buffer[: last_term + 1].strip()
                self._text_buffer = self._text_buffer[last_term + 1 :]

                if sentence:
                    if self._mode == "sync_sentence":
                        await self._synthesize_and_play(sentence)
                    else:
                        self._schedule_synthesis(sentence)

    async def cancel(self) -> None:
        """Cancel all pending synthesis and playback."""
        # Cancel synthesis worker
        if self._synthesis_task and not self._synthesis_task.done():
            self._synthesis_task.cancel()
            with contextlib.suppress(asyncio.CancelledError):
                await self._synthesis_task
            self._synthesis_task = None

        self._drop_queue()
        self._text_buffer = ""

    def _drop_queue(self) -> None:
        while not self._sentence_queue.empty():
            with contextlib.suppress(asyncio.QueueEmpty):
                self._sentence_queue.get_nowait()

    def _raise_worker_error(self) -> None:
        """Raise (once) the error the background worker stopped with."""
        if (error := self._worker_error) is not None:
            self._worker_error = None
            raise error

    async def _flush(self) -> None:
        """Synthesize (sync_sentence) or schedule the rest of the buffer."""
        if text := self._text_buffer.strip():
            self._text_buffer = ""
            if self._mode == "sync_sentence":
                await self._synthesize_and_play(text)
            else:
                self._schedule_synthesis(text)

    async def _close(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Exit the sink and the session (both, even if one fails)."""
        stack, self._exit_stack = self._exit_stack, None
        if stack is not None:
            await stack.__aexit__(exc_type, exc_val, exc_tb)

    async def _abort_and_close(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        try:
            await self.cancel()
        finally:
            await self._close(exc_type, exc_val, exc_tb)

    async def _drain_and_close(self) -> None:
        """Background end of the async modes: finish the queue, then close."""
        try:
            await self._wait_for_completion()
        except BaseException as e:
            if isinstance(e, Exception):
                # kept for wait_closed(); nobody may be waiting, so log it too
                self._worker_error = e
                logger.exception("Background TTS synthesis failed")
            await self._abort_and_close(type(e), e, e.__traceback__)
            if not isinstance(e, Exception):
                raise
        else:
            await self._close(None, None, None)

    async def _synthesize_and_play(self, text: str) -> None:
        """Synthesize text and play audio synchronously.

        Args:
            text: Text to synthesize.
        """
        if not text.strip() or self._sink is None:
            return

        async for chunk in self._session.synthesize(text):
            await self._sink.write(chunk)

    def _schedule_synthesis(self, text: str) -> None:
        """Queue text for background synthesis.

        Args:
            text: Text to synthesize.
        """
        self._raise_worker_error()
        # Start worker if not running
        if self._synthesis_task is None or self._synthesis_task.done():
            self._synthesis_task = asyncio.create_task(self._synthesis_worker())

        # Queue the sentence
        self._sentence_queue.put_nowait(text)

    async def _synthesis_worker(self) -> None:
        """Background worker that processes sentences from the queue.

        A failure stops the worker and drops the queue; the error is raised from
        the next `feed()` or from the context exit.
        """
        try:
            while (sentence := await self._sentence_queue.get()) is not None:
                await self._synthesize_and_play(sentence)
        except Exception as e:  # noqa: BLE001
            self._worker_error = e
            self._drop_queue()

    async def _wait_for_completion(self) -> None:
        """Wait for all pending synthesis and playback to complete."""
        if self._synthesis_task and not self._synthesis_task.done():
            # Signal shutdown and wait
            await self._sentence_queue.put(None)
            await self._synthesis_task
        self._synthesis_task = None
        self._raise_worker_error()

__aenter__ async

__aenter__() -> Self

Enter the stream context, prepare session and sink.

Source code in src/anyvoice/stream.py
async def __aenter__(self) -> Self:
    """Enter the stream context, prepare session and sink."""
    # Initialize sink (default to SoundDeviceSink if not provided)
    if self._sink is None:
        self._sink = SoundDeviceSink()

    async with contextlib.AsyncExitStack() as stack:
        await stack.enter_async_context(self._session)
        await stack.enter_async_context(self._sink)
        self._exit_stack = stack.pop_all()
    self._active = True
    return self

__aexit__ async

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

Exit the stream context, finalize audio and cleanup.

On an exception (or cancellation) inside the context, pending audio is dropped. On a clean exit the remaining text is synthesized; the sync modes wait for it, the async modes leave it to a background task which closes the session and the sink afterwards (see wait_closed()).

Source code in src/anyvoice/stream.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Exit the stream context, finalize audio and cleanup.

    On an exception (or cancellation) inside the context, pending audio is
    dropped. On a clean exit the remaining text is synthesized; the sync modes
    wait for it, the async modes leave it to a background task which closes
    the session and the sink afterwards (see `wait_closed()`).
    """
    self._active = False
    if exc_type is not None:
        await self._abort_and_close(exc_type, exc_val, exc_tb)
        return
    try:
        await self._flush()
        if self._mode == "async_queue":
            task = asyncio.create_task(self._drain_and_close())
            self._closing_task = task
            _background_tasks.add(task)
            task.add_done_callback(_background_tasks.discard)
            return
        await self._wait_for_completion()
    except BaseException as e:
        await self._abort_and_close(type(e), e, e.__traceback__)
        raise
    await self._close(None, None, None)

cancel async

cancel() -> None

Cancel all pending synthesis and playback.

Source code in src/anyvoice/stream.py
async def cancel(self) -> None:
    """Cancel all pending synthesis and playback."""
    # Cancel synthesis worker
    if self._synthesis_task and not self._synthesis_task.done():
        self._synthesis_task.cancel()
        with contextlib.suppress(asyncio.CancelledError):
            await self._synthesis_task
        self._synthesis_task = None

    self._drop_queue()
    self._text_buffer = ""

feed async

feed(text: str) -> None

Feed text to the TTS stream.

Text is buffered until sentence boundaries are detected, then synthesized according to the configured mode.

Parameters:

Name Type Description Default
text str

Text chunk to add to the stream.

required
Source code in src/anyvoice/stream.py
async def feed(self, text: str) -> None:
    """Feed text to the TTS stream.

    Text is buffered until sentence boundaries are detected,
    then synthesized according to the configured mode.

    Args:
        text: Text chunk to add to the stream.
    """
    if not self._active:
        msg = "TTSStream must be used as async context manager"
        raise RuntimeError(msg)
    self._raise_worker_error()

    self._text_buffer += text

    # Check for sentence boundaries
    if any(term in self._text_buffer for term in self._sentence_terminators):
        last_term = max(
            (self._text_buffer.rfind(term) for term in self._sentence_terminators),
            default=-1,
        )

        if last_term > 0 and last_term >= self._min_text_length:
            sentence = self._text_buffer[: last_term + 1].strip()
            self._text_buffer = self._text_buffer[last_term + 1 :]

            if sentence:
                if self._mode == "sync_sentence":
                    await self._synthesize_and_play(sentence)
                else:
                    self._schedule_synthesis(sentence)

wait_closed async

wait_closed() -> None

Wait until background synthesis finished and session and sink are closed.

Only does something after the context exit of the async modes (which don't wait). Raises the error a background synthesis failed with, if any.

Source code in src/anyvoice/stream.py
async def wait_closed(self) -> None:
    """Wait until background synthesis finished and session and sink are closed.

    Only does something after the context exit of the async modes (which don't
    wait). Raises the error a background synthesis failed with, if any.
    """
    if self._closing_task is not None:
        await asyncio.shield(self._closing_task)
    self._raise_worker_error()