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
¶
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
__aenter__
async
¶
__aexit__
async
¶
__aexit__(
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 a PCM audio chunk to the sink.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk
|
bytes
|
Raw PCM audio data (16-bit signed, mono). |
required |
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
__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
write
async
¶
Pass audio chunk to the callback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk
|
bytes
|
PCM audio data. |
required |
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
__aenter__
async
¶
__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).
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
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
__aenter__
async
¶
__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
write
async
¶
Buffer audio chunk for later writing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk
|
bytes
|
PCM audio data to save. |
required |
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
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | |
__aenter__
async
¶
Initialize the OpenAI client shared by the sessions created inside.
__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
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 |
OpenAITTSSession
|
provider's client; otherwise it creates its own and closes it on exit. |
Source code in src/anyvoice/providers/openai.py
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
__aenter__
async
¶
Start the audio output stream.
Source code in src/anyvoice/sinks.py
__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
write
async
¶
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
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
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
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
__aenter__
async
¶
__aexit__
async
¶
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Exit the session context, cleanup resources.
synthesize
abstractmethod
¶
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). |
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
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | |
__aenter__
async
¶
Enter the stream context, prepare session and sink.
Source code in src/anyvoice/stream.py
__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
cancel
async
¶
Cancel all pending synthesis and playback.
Source code in src/anyvoice/stream.py
feed
async
¶
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
wait_closed
async
¶
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.