voiceanim Package¶
Top-Level Facade (voiceanim)¶
voiceanim: Realistic speech synthesis, word-level alignment, and narration sync for handanim.
- class voiceanim.VoiceEngine[source]¶
Bases:
objectUnified facade for voiceanim speech synthesis and narration.
- static get_provider(name='kokoro', **kwargs)[source]¶
Get an initialized provider instance. Defaults to ‘kokoro’.
- Parameters:
- Return type:
- classmethod list_voices(provider='kokoro', category=None, include_blends=False, **kwargs)[source]¶
List available voice IDs for the specified provider (54 built-in voices for Kokoro).
- classmethod blend_voices(voice_spec, **kwargs)[source]¶
Compute a blended (510, 1, 256) float32 style vector across two or more Kokoro voices.
- classmethod synthesize(text, provider='kokoro', voice=None, speed=1.0, instruct=None, output_path=None, preprocess_math=False, lang=None, **kwargs)[source]¶
Synthesize speech using the specified provider (defaulting to Kokoro).
- Parameters:
text (str) – Text to synthesize into speech.
provider (str) – Voice provider (‘kokoro’ [default], ‘polly’, ‘qwen’, ‘mock’).
voice (Any | None) – Voice name, blend expression (e.g.
"am_puck:0.6+bm_fable:0.4"), blend preset (e.g."blend_transatlantic"), weight mapping (e.g.{"am_puck": 0.6, "bm_fable": 0.4}), or(510, 1, 256)style vector.speed (float) – Playback rate multiplier (1.0 = normal).
instruct (str | None) – Prompt instruction for emotion/prosody/timbre (Qwen3-TTS).
output_path (str | Path | None) – Optional explicit output file path.
preprocess_math (bool) – If True, converts inline LaTeX math to spoken English before TTS.
lang (str | None) – Optional phonemizer language code for Kokoro (e.g.,
"en-us","en-gb","es","fr-fr","hi","it","ja","pt-br","cmn").**kwargs (Any) – Extra parameters passed to the provider initializer.
- Returns:
An AudioClip object containing duration and word-level timestamps.
- Return type:
- classmethod synthesize_beats(beats, provider='kokoro', voice=None, speed=1.0, instruct=None, output_dir=None, preprocess_math=False, align='auto', **kwargs)[source]¶
Synthesize a sequence of per-beat narration specs with optional per-beat instruct directions.
Each beat in beats may be a NarrationBeat, a (id, text) 2-tuple, a (id, text, instruct) 3-tuple, or a dict with id/text/instruct/overrides.
- static align_clip(clip, backend='auto', model_size='base', language='en')[source]¶
Run forced alignment on an existing AudioClip to refresh its word timestamps.
- static synthesize_dialogue(turns, output_path=None, speakers=None, default_provider='kokoro', pause_between=0.25, preprocess_math=True, **kwargs)[source]¶
Synthesize a multi-speaker dialogue into a single stitched AudioClip.
- class voiceanim.AudioClip(audio_path, duration, sample_rate=24000, text='', words=<factory>, sentences=<factory>, provider='', voice='', instruct=None, metadata=<factory>)[source]¶
Bases:
objectAudio clip representation with speech marks, alignment timestamps, and metadata.
- Parameters:
- words: list[WordTimestamp]¶
- sentences: list[SentenceTimestamp]¶
- get_word_time(target_word, occurrence=1)[source]¶
Find the start timestamp in seconds of the N-th occurrence of a word.
- get_word_range(target_word, occurrence=1)[source]¶
Find the (start, end) timestamp range of the N-th occurrence of a word.
- export_srt(output_path=None)[source]¶
Export speech marks as standard SubRip (.srt) subtitle string or file.
Uses sentence timestamps when available, falling back to word grouping.
- class voiceanim.WordTimestamp(word, start, end, confidence=1.0, speaker=None)[source]¶
Bases:
objectTimestamp for an individual spoken word.
- class voiceanim.SentenceTimestamp(text, start, end, words=<factory>, speaker=None)[source]¶
Bases:
objectTimestamp for a sentence or complete phrase.
- words: list[WordTimestamp]¶
- class voiceanim.NarrationBeat(id, text, instruct=None, voice=None, provider=None, speed=None, exaggeration=None, cfg_weight=None, controls=None, ref_audio=None, start_time=None, target_duration=None, clip=None)[source]¶
Bases:
objectA designated beat or section in an animation narration script with optional delivery direction.
- Parameters:
- classmethod from_spec(spec)[source]¶
Coerce a beat specification into a NarrationBeat.
Accepts: - NarrationBeat instance - 2-tuple (id, text) - 3-tuple (id, text, instruct) - dict with keys id (or key), text, and optional instruct, voice,
provider, speed, exaggeration, cfg_weight, controls, ref_audio, etc.
- Parameters:
spec (NarrationBeat | dict | tuple | list)
- Return type:
- class voiceanim.AudioCache(cache_dir='.voiceanim_cache')[source]¶
Bases:
objectManages cached synthesized speech waveforms and metadata JSON files.
Guarantees strict reproducibility: identical inputs produce identical hashes, allowing re-renders of whiteboard animations to avoid redundant API or model synthesis.
- Parameters:
cache_dir (str | Path)
- static compute_key(provider, voice, text, speed=1.0, model=None, instruct=None)[source]¶
Generate a SHA-256 hash identifying the exact speech synthesis parameters.
- class voiceanim.ForcedAligner(backend='auto', model_size='base', language='en')[source]¶
Bases:
objectForced word-level aligner supporting neural Whisper backends and acoustic VAD fallback.
- voiceanim.align_words(audio_path, text, *, backend='auto', model_size='base', language='en', duration=None)[source]¶
Convenience function to compute word timestamps for an audio file and script text.
- voiceanim.align_clip(clip, *, backend='auto', model_size='base', language='en')[source]¶
Re-align an existing AudioClip in place and refresh its words and sentences.
- class voiceanim.VoiceTimelineSync[source]¶
Bases:
objectUtilities to synchronize handanim drawing animations with narration timestamps.
- static sync_event_to_word(clip, word, event_cls, drawable, duration=1.5, lead_in=0.0, occurrence=1, **event_kwargs)[source]¶
Create an animation event timed precisely to a spoken word in the narration.
- Parameters:
clip (AudioClip) – Synthesized narration AudioClip with word timestamps.
word (str) – The keyword to synchronize with.
event_cls (type[Any] | Callable[[...], Any]) – Animation class (e.g. SketchAnimation, FadeInAnimation).
drawable (Any) – Target drawable object.
duration (float) – Animation duration.
lead_in (float) – Seconds to start before the word is spoken (e.g. 0.1s for natural pen arrival).
occurrence (int) – Which occurrence of the word to match (1-based).
**event_kwargs (Any) – Extra kwargs passed to the animation event constructor.
- Returns:
Tuple of (initialized_event, drawable).
- Return type:
- static validate_beat_fit(beats)[source]¶
Check whether narration audio fits within designated animation timing slots.
- Parameters:
beats (list[NarrationBeat])
- Return type:
- static stitch_narration_beats(beats, output_path, sample_rate=None, total_duration=None)[source]¶
Combine multiple per-scene narration clips into a single aligned audio track.
Pads with silence between beats so each beat plays at its designated start_time. Preserves native sample rate when
sample_rate=Noneand resamples any mismatched clips.
- voiceanim.mix_audio_with_video(video_path, audio_path, output_path, duration=None, volume=1.0, audio_offset=0.0, shortest=True, loop_audio=False)[source]¶
Mux an audio track (WAV/MP3) with an existing MP4 video file.
Uses imageio-ffmpeg’s bundled ffmpeg binary for zero external system dependencies.
- Parameters:
video_path (str | Path) – Path to source silent or existing video.
duration (float | None) – Optional maximum duration in seconds.
volume (float) – Audio volume multiplier (1.0 = normal).
audio_offset (float) – Optional audio start delay in seconds.
shortest (bool) – End muxing when the shortest stream ends (default True).
loop_audio (bool) – If True, loop the audio input indefinitely up to the video length.
- Returns:
The resolved output video path string.
- Return type:
- voiceanim.mix_soundtrack(duration, narration=None, background_music=None, music_volume=0.18, music_loop=True, duck_music=True, sfx_events=None, output_path=None, sample_rate=44100, target_lufs=-14.0, ceiling_dbfs=-1.5, stereo=True)[source]¶
Mix narration, repeating background theme music, and timed SFX (chalk, eraser, etc.) into a WAV file.
- Parameters:
duration (float) – Total duration of the soundtrack in seconds.
narration (Any) – Optional AudioClip or path to a narration audio file.
background_music (Any) – Optional background music source: - True or “marimba” / “theme” / “calm” / “upbeat” for built-in open-source theme music - Path to an audio file (.wav, .mp3, etc.) or an AudioClip
music_volume (float) – Volume multiplier for the background music track (default 0.18).
music_loop (bool) – Whether to repeat the background music across the full duration (default True).
duck_music (bool) – Whether to automatically duck background music volume while speech is active.
sfx_events (Sequence[dict[str, Any] | tuple[Any, ...]] | None) – List of sound effect dicts {“type”: “chalk”|”eraser”|…, “start_time”: float, “duration”: float, “volume”: float} or tuples (start_time, kind, duration[, volume]).
output_path (str | Path | None) – Destination .wav file path. If None, creates a temporary .wav file.
sample_rate (int) – Sample rate in Hz (default 44100).
target_lufs (float | None)
ceiling_dbfs (float)
stereo (bool)
- Returns:
Path to the mixed .wav file.
- Return type:
- voiceanim.generate_theme_music(duration, output_path=None, style='marimba', bpm=104.0, volume=0.22, fade_in=0.3, fade_out=0.8, sample_rate=44100)[source]¶
Generate a repeating open-source background theme music track for duration seconds.
- Parameters:
duration (float) – Total duration in seconds.
output_path (str | Path | None) – Optional destination .wav path. Uses a temporary file if omitted.
style (str) – Theme preset (“marimba”, “theme”, “calm”, or “upbeat”).
bpm (float) – Tempo in beats per minute.
volume (float) – Output amplitude scaling (default 0.22 for background music).
fade_in (float) – Fade-in duration in seconds.
fade_out (float) – Fade-out duration in seconds.
sample_rate (int) – Sample rate in Hz.
- Returns:
An AudioClip pointing to the generated WAV file.
- Return type:
- voiceanim.loop_audio(audio_source, duration, output_path=None, volume=0.22, fade_in=0.3, fade_out=0.8, sample_rate=44100)[source]¶
Repeat an audio file, AudioClip, or built-in theme preset to fill duration seconds.
- Parameters:
audio_source (str | Path | AudioClip | Any) – Path to a WAV/MP3 audio file, an AudioClip, or a preset name (“marimba”, “theme”, “calm”, “upbeat”).
duration (float) – Target total duration in seconds.
output_path (str | Path | None) – Optional destination .wav file path.
volume (float) – Volume multiplier applied to the looped audio.
fade_in (float) – Fade-in duration at the start (seconds).
fade_out (float) – Fade-out duration at the end (seconds).
sample_rate (int) – Audio sample rate in Hz.
- Returns:
An AudioClip pointing to the looped WAV file.
- Return type:
- voiceanim.synthesize_chalk_sound(duration, sample_rate=44100, seed=42, style='chalk', volume=0.25)[source]¶
Synthesize an open-source chalk or sketch-pen drawing sound over duration seconds.
Combines: - Initial chalk-to-board contact tap transient - Balanced chalky grain (1500-5200 Hz) + warm board resonance (650-1650 Hz) - Hand-stroke velocity modulation (8-14 Hz) with natural micro-lifts between sub-strokes
- voiceanim.synthesize_eraser_sound(duration, sample_rate=44100, seed=101, volume=0.55)[source]¶
Synthesize an open-source felt/rubber eraser wiping sound over duration seconds.
Models a rhythmic back-and-forth zigzag wiping motion across the board: - Soft low-mid felt friction (280-1900 Hz) + warm board rub (160-520 Hz) - Alternating forward/backward swipe envelope (4.5-6.5 swipes/sec)
- voiceanim.synthesize_page_turn_sound(duration=0.9, sample_rate=44100, seed=55, volume=0.5)[source]¶
Synthesize an open-source paper page-turn / sheet-folding sound over duration seconds.
Combines: - Subtle initial corner-lift paper flick - Smoothly swept paper-on-paper sliding friction (900-5800 Hz) - Gentle settling crease pat near the end of the turn
- voiceanim.synthesize_crumple_sound(duration=1.0, sample_rate=44100, seed=88, volume=0.55)[source]¶
Synthesize an open-source paper crumpling and toss sound over duration seconds.
Combines: - A dense cascade of dry, crisp paper-crinkle micro-bursts (1.4-8.5 kHz) + stiff paper snaps (0..70% of duration) - A light aerodynamic toss whoosh (55..100% of duration) as the crumpled ball flies off to the side
- voiceanim.synthesize_pop_sound(pitch=1.0, sample_rate=44100, volume=0.5)[source]¶
Synthesize a crisp cartoon pop sound effect (~12 dB under active speech at typical volumes).
- voiceanim.synthesize_whoosh_sound(duration=0.38, sample_rate=44100, volume=0.45)[source]¶
Synthesize a smooth transition whoosh sound effect (~12 dB under active speech).
- voiceanim.synthesize_ding_sound(sample_rate=44100, volume=0.45)[source]¶
Synthesize a pleasant two-note bell ding sound effect (~12 dB under active speech).
- voiceanim.synthesize_theme_loop(bars=4, bpm=104.0, style='marimba', sample_rate=44100)[source]¶
Synthesize a seamless multi-bar open-source background theme loop.
Supported styles: -
"marimba"/"theme": Warm marimba arpeggio + soft bass + light shaker (default) -"calm": Gentle acoustic/electric-piano warm chord progression without percussion -"upbeat": Brighter tempo-locked marimba + pulse
- class voiceanim.BaseVoiceProvider[source]¶
Bases:
ABCAbstract interface for a text-to-speech provider.
- abstractmethod synthesize(text, voice=None, speed=1.0, instruct=None, output_path=None, **kwargs)[source]¶
Synthesize text into speech and return an AudioClip with timestamps.
- Parameters:
text (str) – Text to speak.
voice (str | None) – Voice name or ID. If None, uses default_voice.
speed (float) – Speech rate multiplier (1.0 = normal).
instruct (str | None) – Natural language instruction for tone/prosody/emotion (used by Qwen3-TTS).
output_path (str | Path | None) – Optional explicit output WAV path. If None, writes to a temp or cache path.
**kwargs (Any) – Extra provider-specific parameters.
- Returns:
An AudioClip instance containing the path, duration, and word timestamps.
- Return type:
- static estimate_word_timings(text, total_duration, start_offset=0.05)[source]¶
Heuristically estimate word timestamps proportional to character length and punctuation.
Used when a provider returns audio without native alignment speech marks.
- Parameters:
- Return type:
- static extract_sentences(text, word_timings)[source]¶
Group word timestamps into sentence boundaries based on terminal punctuation.
- Parameters:
text (str)
word_timings (list[WordTimestamp])
- Return type:
- class voiceanim.ChatterboxProvider(model_id=None, backend='auto', device='auto', ref_audio=None, exaggeration=None, cfg_weight=None, temperature=None, align_backend='auto', cache=None, fallback_to_mock=False)[source]¶
Bases:
BaseVoiceProviderExpressive speech synthesis provider backed by Resemble AI Chatterbox.
- Parameters:
- supported_voices: list[str] = ['default', 'energetic', 'dramatic', 'playful', 'calm', 'storyteller']¶
- class voiceanim.KokoroProvider(model_dir=None, cache=None, fallback_to_mock=False)[source]¶
Bases:
BaseVoiceProviderLocal, offline text-to-speech provider using the Kokoro-82M model.
Supports all 54 built-in Kokoro v1.0 voices as well as arbitrary weighted blends of voices in the 256-D style embedding space: - Single voice ID:
voice="am_fenrir",voice="bm_fable",voice="af_aoede"- Named blend preset:voice="blend_transatlantic",voice="blend_professor"- Weighted blend string:voice="am_puck:0.6+bm_fable:0.4"or"am_puck:60,bm_fable:40"- Equal-weight blend string:voice="am_puck+bm_fable"(50% / 50%) - Dictionary of weights:voice={"am_puck": 0.6, "bm_fable": 0.4}- Sequence of(voice, weight)pairs or voice names:voice=[("am_puck", 0.6), ("bm_fable", 0.4)]- Pre-computed(510, 1, 256)float32 NumPy style array- Parameters:
model_dir (str | Path | None)
cache (AudioCache | None)
fallback_to_mock (bool)
- supported_voices: list[str] = ['af_alloy', 'af_aoede', 'af_bella', 'af_heart', 'af_jessica', 'af_kore', 'af_nicole', 'af_nova', 'af_river', 'af_sarah', 'af_sky', 'am_adam', 'am_echo', 'am_eric', 'am_fenrir', 'am_liam', 'am_michael', 'am_onyx', 'am_puck', 'am_santa', 'bf_alice', 'bf_emma', 'bf_isabella', 'bf_lily', 'bm_daniel', 'bm_fable', 'bm_george', 'bm_lewis', 'ef_dora', 'em_alex', 'em_santa', 'ff_siwis', 'hf_alpha', 'hf_beta', 'hm_omega', 'hm_psi', 'if_sara', 'im_nicola', 'jf_alpha', 'jf_gongitsune', 'jf_nezumi', 'jf_tebukuro', 'jm_kumo', 'pf_dora', 'pm_alex', 'pm_santa', 'zf_xiaobei', 'zf_xiaoni', 'zf_xiaoxiao', 'zf_xiaoyi', 'zm_yunjian', 'zm_yunxi', 'zm_yunxia', 'zm_yunyang']¶
- voice_catalog = {'american_female': ['af_alloy', 'af_aoede', 'af_bella', 'af_heart', 'af_jessica', 'af_kore', 'af_nicole', 'af_nova', 'af_river', 'af_sarah', 'af_sky'], 'american_male': ['am_adam', 'am_echo', 'am_eric', 'am_fenrir', 'am_liam', 'am_michael', 'am_onyx', 'am_puck', 'am_santa'], 'british_female': ['bf_alice', 'bf_emma', 'bf_isabella', 'bf_lily'], 'british_male': ['bm_daniel', 'bm_fable', 'bm_george', 'bm_lewis'], 'french': ['ff_siwis'], 'hindi': ['hf_alpha', 'hf_beta', 'hm_omega', 'hm_psi'], 'italian': ['if_sara', 'im_nicola'], 'japanese': ['jf_alpha', 'jf_gongitsune', 'jf_nezumi', 'jf_tebukuro', 'jm_kumo'], 'mandarin': ['zf_xiaobei', 'zf_xiaoni', 'zf_xiaoxiao', 'zf_xiaoyi', 'zm_yunjian', 'zm_yunxi', 'zm_yunxia', 'zm_yunyang'], 'portuguese': ['pf_dora', 'pm_alex', 'pm_santa'], 'spanish': ['ef_dora', 'em_alex', 'em_santa']}¶
- blend_presets = {'blend_host_female': 'af_aoede:0.6+af_kore:0.4', 'blend_indian_female': 'hf_alpha:0.55+af_aoede:0.45', 'blend_indian_male': 'hm_omega:0.55+am_liam:0.45', 'blend_professor': 'am_fenrir:0.55+am_onyx:0.45', 'blend_storyteller': 'bm_fable:0.6+am_liam:0.4', 'blend_transatlantic': 'am_puck:0.6+bm_fable:0.4', 'studio_host_f': 'af_aoede:0.6+af_kore:0.4', 'studio_indian_en': 'hm_omega:0.55+am_liam:0.45', 'studio_indian_f': 'hf_alpha:0.55+af_aoede:0.45', 'studio_professor': 'am_fenrir:0.55+am_onyx:0.45', 'studio_transatlantic': 'am_puck:0.6+bm_fable:0.4'}¶
- list_voices(category=None, include_blends=False)[source]¶
Return available Kokoro voice IDs.
- Parameters:
- Return type:
- classmethod parse_voice_spec(voice_spec, available_voices=None)[source]¶
Parse a voice name, blend expression, dict, or sequence into normalized
(voice_id, weight)pairs.Weights are normalized so that they sum to
1.0.
- classmethod format_voice_spec(voice_spec, available_voices=None)[source]¶
Convert any voice specification into a canonical string label for caching and metadata.
- classmethod infer_language(voice_spec, native_non_english=False)[source]¶
Infer espeak-ng phonemizer language code from the dominant voice in voice_spec.
By default (native_non_english=False), British voices (bf_*, bm_*) select “en-gb” and all other voices default to “en-us” so cross-accent voices (e.g. hm_omega, hf_alpha) speak English scripts seamlessly. When native_non_english=True, non-English prefixes map to their native espeak-ng language code (“es”, “fr-fr”, “hi”, “it”, “ja”, “pt-br”, “cmn”).
- blend_voices(voice_spec)[source]¶
Compute a blended (510, 1, 256) float32 style embedding from two or more Kokoro voices.
- Parameters:
voice_spec (str | Mapping[str, float] | Sequence[tuple[str, float] | str]) – A blend string (e.g.
"am_puck:0.6+bm_fable:0.4"or"am_puck+bm_fable"), preset name (e.g."blend_transatlantic"), dict{"am_puck": 0.6, "bm_fable": 0.4}, or sequence of(voice_name, weight)pairs.- Returns:
A
(510, 1, 256)float32 NumPy style vector suitable for passing tosynthesize(voice=...).- Return type:
- synthesize(text, voice=None, speed=1.0, instruct=None, output_path=None, lang=None, **kwargs)[source]¶
Synthesize text into speech and return an AudioClip with timestamps.
- Parameters:
text (str) – Text to speak.
voice (str | Mapping[str, float] | Sequence[tuple[str, float] | str] | ndarray | None) – Voice name or ID. If None, uses default_voice.
speed (float) – Speech rate multiplier (1.0 = normal).
instruct (str | None) – Natural language instruction for tone/prosody/emotion (used by Qwen3-TTS).
output_path (str | Path | None) – Optional explicit output WAV path. If None, writes to a temp or cache path.
**kwargs (Any) – Extra provider-specific parameters.
lang (str | None)
**kwargs
- Returns:
An AudioClip instance containing the path, duration, and word timestamps.
- Return type:
- class voiceanim.PollyProvider(engine='neural', region_name=None, cache=None)[source]¶
Bases:
BaseVoiceProviderAWS Polly text-to-speech provider.
Leverages AWS Polly Neural and Generative engines, and extracts native word-level and sentence-level SpeechMarks for precise whiteboard visual sync.
- Parameters:
engine (str)
region_name (str | None)
cache (AudioCache | None)
- supported_voices: list[str] = ['Matthew', 'Ruth', 'Joanna', 'Stephen', 'Danielle', 'Gregory', 'Amy', 'Olivia']¶
- synthesize(text, voice=None, speed=1.0, instruct=None, output_path=None, **kwargs)[source]¶
Synthesize text into speech and return an AudioClip with timestamps.
- Parameters:
text (str) – Text to speak.
voice (str | None) – Voice name or ID. If None, uses default_voice.
speed (float) – Speech rate multiplier (1.0 = normal).
instruct (str | None) – Natural language instruction for tone/prosody/emotion (used by Qwen3-TTS).
output_path (str | Path | None) – Optional explicit output WAV path. If None, writes to a temp or cache path.
**kwargs (Any) – Extra provider-specific parameters.
- Returns:
An AudioClip instance containing the path, duration, and word timestamps.
- Return type:
- class voiceanim.QwenTTSProvider(model_id='Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice', cache=None, hf_token=None, device='auto', fallback_to_mock=False)[source]¶
Bases:
BaseVoiceProviderQwen3-TTS model provider supporting natural language instruction prompts.
- Allows fine-grained, prompt-based control over emotion, prosody, and style:
engine.synthesize(”…”, instruct=”Speak with inquisitive warmth, pausing after questions”)
- Parameters:
model_id (str)
cache (AudioCache | None)
hf_token (str | None)
device (str)
fallback_to_mock (bool)
- synthesize(text, voice=None, speed=1.0, instruct=None, output_path=None, language='English', **kwargs)[source]¶
Synthesize text into speech and return an AudioClip with timestamps.
- Parameters:
text (str) – Text to speak.
voice (str | None) – Voice name or ID. If None, uses default_voice.
speed (float) – Speech rate multiplier (1.0 = normal).
instruct (str | None) – Natural language instruction for tone/prosody/emotion (used by Qwen3-TTS).
output_path (str | Path | None) – Optional explicit output WAV path. If None, writes to a temp or cache path.
**kwargs (Any) – Extra provider-specific parameters.
language (str)
**kwargs
- Returns:
An AudioClip instance containing the path, duration, and word timestamps.
- Return type:
- class voiceanim.ZonosProvider(model_id=None, backend='auto', api_url=None, device='auto', ref_audio=None, language='en-us', align_backend='auto', cache=None, fallback_to_mock=False)[source]¶
Bases:
BaseVoiceProviderExpressive speech synthesis provider backed by Zyphra ZONOS3-Mini.
- Parameters:
- supported_voices: list[str] = ['ananya', 'arjun', 'chaitanya', 'cillian', 'gaspard', 'ginevra', 'haoran', 'imogen', 'jett', 'leonor', 'liesel', 'lorenzo', 'meilin', 'minjun', 'morgana', 'rodrigo', 'rupert', 'sakura', 'savannah', 'seoyeon', 'sravya', 'thaddeus', 'thiago', 'willow', 'wolfgang', 'wyatt', 'ximena']¶
- synthesize(text, voice=None, speed=1.0, instruct=None, output_path=None, *, ref_audio=None, language=None, controls=None, control_spans=None, condition_values=None, speaker_cfg_scale=None, temperature=None, seed=None, align='auto', **kwargs)[source]¶
Synthesize speech with ZONOS3-Mini using steering controls or zero-shot cloning.
- class voiceanim.MockVoiceProvider(cache=None, words_per_minute=160.0)[source]¶
Bases:
BaseVoiceProviderDeterministic mock provider that generates synthetic tone WAV files with word timestamps.
- Parameters:
cache (AudioCache | None)
words_per_minute (float)
- synthesize(text, voice=None, speed=1.0, instruct=None, output_path=None, **kwargs)[source]¶
Synthesize text into speech and return an AudioClip with timestamps.
- Parameters:
text (str) – Text to speak.
voice (str | None) – Voice name or ID. If None, uses default_voice.
speed (float) – Speech rate multiplier (1.0 = normal).
instruct (str | None) – Natural language instruction for tone/prosody/emotion (used by Qwen3-TTS).
output_path (str | Path | None) – Optional explicit output WAV path. If None, writes to a temp or cache path.
**kwargs (Any) – Extra provider-specific parameters.
- Returns:
An AudioClip instance containing the path, duration, and word timestamps.
- Return type:
- voiceanim.get_provider(name='kokoro', **kwargs)[source]¶
Retrieve an initialized voice provider instance.
- Parameters:
- Returns:
An instance of BaseVoiceProvider.
- Return type:
- voiceanim.latex_to_speech(text)[source]¶
Convert a string containing LaTeX math ($…$, $$…$$, or raw LaTeX) into natural spoken English.
If text contains delimited math spans ($$…$$, $…$, (…), […]), each math span is converted while surrounding prose is preserved (with any stray Unicode math symbols or inline LaTeX commands also expanded). If text has no $ delimiters but contains LaTeX math commands (like frac, int, sum, ^, _), the entire string is converted as a math expression.
Examples:
>>> latex_to_speech("Euler's identity is $e^{i\pi} + 1 = 0$.") "Euler's identity is e to the i pi plus 1 equals 0." >>> latex_to_speech(r"\int_0^\pi \sin(x) dx = 2") 'the integral from 0 to pi of sine x d x equals 2'
- class voiceanim.DialogueTurn(speaker, text, voice=None, provider=None, speed=None, instruct=None, pause_after=None)[source]¶
Bases:
objectA single spoken turn in a multi-speaker dialogue.
- Parameters:
- class voiceanim.SpeakerProfile(name, voice='af_heart', provider='kokoro', speed=1.0, instruct=None, color=None, highlight=None)[source]¶
Bases:
objectVoice and visual theme configuration for a dialogue participant.
- Parameters:
- voiceanim.synthesize_dialogue(turns, output_path=None, speakers=None, default_provider='kokoro', pause_between=0.25, preprocess_math=True, sample_rate=24000, **provider_kwargs)[source]¶
Synthesize a multi-speaker dialogue into a single stitched AudioClip.
Each word and sentence timestamp in the returned AudioClip carries its speaker name, and clip.metadata[“turns”] / clip.metadata[“speakers”] record per-turn boundaries and speaker color themes for Captions.
- Parameters:
turns (Sequence[DialogueTurn | dict[str, Any] | tuple[str, str]]) – Sequence of DialogueTurn objects, dicts {“speaker”: …, “text”: …}, or (speaker, text) tuples.
output_path (str | Path | None) – Optional output WAV path. If omitted, writes to a temporary file.
speakers (dict[str, SpeakerProfile | dict[str, Any] | str] | None) – Optional mapping from speaker name to SpeakerProfile, config dict, or voice ID string (e.g. {“student”: “am_adam”, “professor”: “af_heart”}).
default_provider (str) – Default provider when not specified by speaker/turn (“kokoro”).
pause_between (float) – Default silence padding in seconds between consecutive turns.
preprocess_math (bool) – If True (default), runs latex_to_speech on each turn’s text.
sample_rate (int) – Output WAV sample rate (default 24000).
provider_kwargs (Any)
- Return type:
voiceanim.schema¶
Data models and schemas for voiceanim speech synthesis, timestamps, and narration.
- class voiceanim.schema.WordTimestamp(word, start, end, confidence=1.0, speaker=None)[source]¶
Bases:
objectTimestamp for an individual spoken word.
- class voiceanim.schema.SentenceTimestamp(text, start, end, words=<factory>, speaker=None)[source]¶
Bases:
objectTimestamp for a sentence or complete phrase.
- words: list[WordTimestamp]¶
- class voiceanim.schema.AudioClip(audio_path, duration, sample_rate=24000, text='', words=<factory>, sentences=<factory>, provider='', voice='', instruct=None, metadata=<factory>)[source]¶
Bases:
objectAudio clip representation with speech marks, alignment timestamps, and metadata.
- Parameters:
- words: list[WordTimestamp]¶
- sentences: list[SentenceTimestamp]¶
- get_word_time(target_word, occurrence=1)[source]¶
Find the start timestamp in seconds of the N-th occurrence of a word.
- get_word_range(target_word, occurrence=1)[source]¶
Find the (start, end) timestamp range of the N-th occurrence of a word.
- export_srt(output_path=None)[source]¶
Export speech marks as standard SubRip (.srt) subtitle string or file.
Uses sentence timestamps when available, falling back to word grouping.
- class voiceanim.schema.NarrationBeat(id, text, instruct=None, voice=None, provider=None, speed=None, exaggeration=None, cfg_weight=None, controls=None, ref_audio=None, start_time=None, target_duration=None, clip=None)[source]¶
Bases:
objectA designated beat or section in an animation narration script with optional delivery direction.
- Parameters:
- classmethod from_spec(spec)[source]¶
Coerce a beat specification into a NarrationBeat.
Accepts: - NarrationBeat instance - 2-tuple (id, text) - 3-tuple (id, text, instruct) - dict with keys id (or key), text, and optional instruct, voice,
provider, speed, exaggeration, cfg_weight, controls, ref_audio, etc.
- Parameters:
spec (NarrationBeat | dict | tuple | list)
- Return type:
voiceanim.timeline¶
Animation timeline synchronization with spoken narration.
- class voiceanim.timeline.VoiceTimelineSync[source]¶
Bases:
objectUtilities to synchronize handanim drawing animations with narration timestamps.
- static sync_event_to_word(clip, word, event_cls, drawable, duration=1.5, lead_in=0.0, occurrence=1, **event_kwargs)[source]¶
Create an animation event timed precisely to a spoken word in the narration.
- Parameters:
clip (AudioClip) – Synthesized narration AudioClip with word timestamps.
word (str) – The keyword to synchronize with.
event_cls (type[Any] | Callable[[...], Any]) – Animation class (e.g. SketchAnimation, FadeInAnimation).
drawable (Any) – Target drawable object.
duration (float) – Animation duration.
lead_in (float) – Seconds to start before the word is spoken (e.g. 0.1s for natural pen arrival).
occurrence (int) – Which occurrence of the word to match (1-based).
**event_kwargs (Any) – Extra kwargs passed to the animation event constructor.
- Returns:
Tuple of (initialized_event, drawable).
- Return type:
- static validate_beat_fit(beats)[source]¶
Check whether narration audio fits within designated animation timing slots.
- Parameters:
beats (list[NarrationBeat])
- Return type:
- static stitch_narration_beats(beats, output_path, sample_rate=None, total_duration=None)[source]¶
Combine multiple per-scene narration clips into a single aligned audio track.
Pads with silence between beats so each beat plays at its designated start_time. Preserves native sample rate when
sample_rate=Noneand resamples any mismatched clips.
voiceanim.sfx¶
Open-source procedural sound effects (chalk sketch, eraser, UI SFX) and looping background music.
- voiceanim.sfx.write_wav_mono(path, samples, sample_rate=44100)[source]¶
Write a 1D (mono) or 2D (N, C) float64 numpy array in [-1, 1] to a 16-bit PCM WAV file.
- voiceanim.sfx.write_wav_stereo(path, samples, sample_rate=44100)[source]¶
Write a 1D or (N, 2) float64 array to a 2-channel 16-bit PCM stereo WAV file.
- voiceanim.sfx.read_audio_mono(path, target_sr=44100)[source]¶
Read any audio file (.wav, .mp3, .ogg, .m4a) into a 1D float64 array at target_sr.
- voiceanim.sfx.synthesize_chalk_sound(duration, sample_rate=44100, seed=42, style='chalk', volume=0.25)[source]¶
Synthesize an open-source chalk or sketch-pen drawing sound over duration seconds.
Combines: - Initial chalk-to-board contact tap transient - Balanced chalky grain (1500-5200 Hz) + warm board resonance (650-1650 Hz) - Hand-stroke velocity modulation (8-14 Hz) with natural micro-lifts between sub-strokes
- voiceanim.sfx.synthesize_eraser_sound(duration, sample_rate=44100, seed=101, volume=0.55)[source]¶
Synthesize an open-source felt/rubber eraser wiping sound over duration seconds.
Models a rhythmic back-and-forth zigzag wiping motion across the board: - Soft low-mid felt friction (280-1900 Hz) + warm board rub (160-520 Hz) - Alternating forward/backward swipe envelope (4.5-6.5 swipes/sec)
- voiceanim.sfx.synthesize_pop_sound(pitch=1.0, sample_rate=44100, volume=0.5)[source]¶
Synthesize a crisp cartoon pop sound effect (~12 dB under active speech at typical volumes).
- voiceanim.sfx.synthesize_whoosh_sound(duration=0.38, sample_rate=44100, volume=0.45)[source]¶
Synthesize a smooth transition whoosh sound effect (~12 dB under active speech).
- voiceanim.sfx.synthesize_ding_sound(sample_rate=44100, volume=0.45)[source]¶
Synthesize a pleasant two-note bell ding sound effect (~12 dB under active speech).
- voiceanim.sfx.synthesize_page_turn_sound(duration=0.9, sample_rate=44100, seed=55, volume=0.5)[source]¶
Synthesize an open-source paper page-turn / sheet-folding sound over duration seconds.
Combines: - Subtle initial corner-lift paper flick - Smoothly swept paper-on-paper sliding friction (900-5800 Hz) - Gentle settling crease pat near the end of the turn
- voiceanim.sfx.synthesize_crumple_sound(duration=1.0, sample_rate=44100, seed=88, volume=0.55)[source]¶
Synthesize an open-source paper crumpling and toss sound over duration seconds.
Combines: - A dense cascade of dry, crisp paper-crinkle micro-bursts (1.4-8.5 kHz) + stiff paper snaps (0..70% of duration) - A light aerodynamic toss whoosh (55..100% of duration) as the crumpled ball flies off to the side
- voiceanim.sfx.synthesize_theme_loop(bars=4, bpm=104.0, style='marimba', sample_rate=44100)[source]¶
Synthesize a seamless multi-bar open-source background theme loop.
Supported styles: -
"marimba"/"theme": Warm marimba arpeggio + soft bass + light shaker (default) -"calm": Gentle acoustic/electric-piano warm chord progression without percussion -"upbeat": Brighter tempo-locked marimba + pulse
- voiceanim.sfx.loop_audio_array(audio, duration, sample_rate=44100, crossfade=0.04, fade_in=0.25, fade_out=0.6, volume=1.0)[source]¶
Repeat a 1D audio array seamlessly to fill duration seconds.
- voiceanim.sfx.generate_theme_music(duration, output_path=None, style='marimba', bpm=104.0, volume=0.22, fade_in=0.3, fade_out=0.8, sample_rate=44100)[source]¶
Generate a repeating open-source background theme music track for duration seconds.
- Parameters:
duration (float) – Total duration in seconds.
output_path (str | Path | None) – Optional destination .wav path. Uses a temporary file if omitted.
style (str) – Theme preset (“marimba”, “theme”, “calm”, or “upbeat”).
bpm (float) – Tempo in beats per minute.
volume (float) – Output amplitude scaling (default 0.22 for background music).
fade_in (float) – Fade-in duration in seconds.
fade_out (float) – Fade-out duration in seconds.
sample_rate (int) – Sample rate in Hz.
- Returns:
An AudioClip pointing to the generated WAV file.
- Return type:
- voiceanim.sfx.loop_audio(audio_source, duration, output_path=None, volume=0.22, fade_in=0.3, fade_out=0.8, sample_rate=44100)[source]¶
Repeat an audio file, AudioClip, or built-in theme preset to fill duration seconds.
- Parameters:
audio_source (str | Path | AudioClip | Any) – Path to a WAV/MP3 audio file, an AudioClip, or a preset name (“marimba”, “theme”, “calm”, “upbeat”).
duration (float) – Target total duration in seconds.
output_path (str | Path | None) – Optional destination .wav file path.
volume (float) – Volume multiplier applied to the looped audio.
fade_in (float) – Fade-in duration at the start (seconds).
fade_out (float) – Fade-out duration at the end (seconds).
sample_rate (int) – Audio sample rate in Hz.
- Returns:
An AudioClip pointing to the looped WAV file.
- Return type:
voiceanim.mixer¶
Audio and video multiplexing and multi-track soundtrack mixing.
- voiceanim.mixer.measure_integrated_lufs(audio, sample_rate=44100)[source]¶
Measure ITU-R BS.1770-4 integrated loudness in LUFS.
- voiceanim.mixer.normalize_and_limit(audio, sample_rate=44100, target_lufs=-14.0, ceiling_dbfs=-1.5)[source]¶
Normalize integrated loudness to target_lufs (-14 LUFS default) with a true-peak soft-knee limiter.
- voiceanim.mixer.mix_soundtrack(duration, narration=None, background_music=None, music_volume=0.18, music_loop=True, duck_music=True, sfx_events=None, output_path=None, sample_rate=44100, target_lufs=-14.0, ceiling_dbfs=-1.5, stereo=True)[source]¶
Mix narration, repeating background theme music, and timed SFX (chalk, eraser, etc.) into a WAV file.
- Parameters:
duration (float) – Total duration of the soundtrack in seconds.
narration (Any) – Optional AudioClip or path to a narration audio file.
background_music (Any) – Optional background music source: - True or “marimba” / “theme” / “calm” / “upbeat” for built-in open-source theme music - Path to an audio file (.wav, .mp3, etc.) or an AudioClip
music_volume (float) – Volume multiplier for the background music track (default 0.18).
music_loop (bool) – Whether to repeat the background music across the full duration (default True).
duck_music (bool) – Whether to automatically duck background music volume while speech is active.
sfx_events (Sequence[dict[str, Any] | tuple[Any, ...]] | None) – List of sound effect dicts {“type”: “chalk”|”eraser”|…, “start_time”: float, “duration”: float, “volume”: float} or tuples (start_time, kind, duration[, volume]).
output_path (str | Path | None) – Destination .wav file path. If None, creates a temporary .wav file.
sample_rate (int) – Sample rate in Hz (default 44100).
target_lufs (float | None)
ceiling_dbfs (float)
stereo (bool)
- Returns:
Path to the mixed .wav file.
- Return type:
- voiceanim.mixer.mix_audio_with_video(video_path, audio_path, output_path, duration=None, volume=1.0, audio_offset=0.0, shortest=True, loop_audio=False)[source]¶
Mux an audio track (WAV/MP3) with an existing MP4 video file.
Uses imageio-ffmpeg’s bundled ffmpeg binary for zero external system dependencies.
- Parameters:
video_path (str | Path) – Path to source silent or existing video.
duration (float | None) – Optional maximum duration in seconds.
volume (float) – Audio volume multiplier (1.0 = normal).
audio_offset (float) – Optional audio start delay in seconds.
shortest (bool) – End muxing when the shortest stream ends (default True).
loop_audio (bool) – If True, loop the audio input indefinitely up to the video length.
- Returns:
The resolved output video path string.
- Return type:
voiceanim.cache¶
Content-addressed audio cache for deterministic and reproducible voice generation.
- class voiceanim.cache.AudioCache(cache_dir='.voiceanim_cache')[source]¶
Bases:
objectManages cached synthesized speech waveforms and metadata JSON files.
Guarantees strict reproducibility: identical inputs produce identical hashes, allowing re-renders of whiteboard animations to avoid redundant API or model synthesis.
- Parameters:
cache_dir (str | Path)
- static compute_key(provider, voice, text, speed=1.0, model=None, instruct=None)[source]¶
Generate a SHA-256 hash identifying the exact speech synthesis parameters.
voiceanim.providers¶
Abstract base class and utilities for speech synthesis providers.
- class voiceanim.providers.base.BaseVoiceProvider[source]¶
Bases:
ABCAbstract interface for a text-to-speech provider.
- abstractmethod synthesize(text, voice=None, speed=1.0, instruct=None, output_path=None, **kwargs)[source]¶
Synthesize text into speech and return an AudioClip with timestamps.
- Parameters:
text (str) – Text to speak.
voice (str | None) – Voice name or ID. If None, uses default_voice.
speed (float) – Speech rate multiplier (1.0 = normal).
instruct (str | None) – Natural language instruction for tone/prosody/emotion (used by Qwen3-TTS).
output_path (str | Path | None) – Optional explicit output WAV path. If None, writes to a temp or cache path.
**kwargs (Any) – Extra provider-specific parameters.
- Returns:
An AudioClip instance containing the path, duration, and word timestamps.
- Return type:
- static estimate_word_timings(text, total_duration, start_offset=0.05)[source]¶
Heuristically estimate word timestamps proportional to character length and punctuation.
Used when a provider returns audio without native alignment speech marks.
- Parameters:
- Return type:
- static extract_sentences(text, word_timings)[source]¶
Group word timestamps into sentence boundaries based on terminal punctuation.
- Parameters:
text (str)
word_timings (list[WordTimestamp])
- Return type:
Kokoro-82M local offline TTS provider.
High-fidelity, 82M-parameter lightweight open-weight TTS model running on macOS via ONNX runtime or PyTorch, supporting all 54 built-in voice embeddings as well as arbitrary 256-D latent style-vector blending across voices.
- class voiceanim.providers.kokoro_provider.KokoroProvider(model_dir=None, cache=None, fallback_to_mock=False)[source]¶
Bases:
BaseVoiceProviderLocal, offline text-to-speech provider using the Kokoro-82M model.
Supports all 54 built-in Kokoro v1.0 voices as well as arbitrary weighted blends of voices in the 256-D style embedding space: - Single voice ID:
voice="am_fenrir",voice="bm_fable",voice="af_aoede"- Named blend preset:voice="blend_transatlantic",voice="blend_professor"- Weighted blend string:voice="am_puck:0.6+bm_fable:0.4"or"am_puck:60,bm_fable:40"- Equal-weight blend string:voice="am_puck+bm_fable"(50% / 50%) - Dictionary of weights:voice={"am_puck": 0.6, "bm_fable": 0.4}- Sequence of(voice, weight)pairs or voice names:voice=[("am_puck", 0.6), ("bm_fable", 0.4)]- Pre-computed(510, 1, 256)float32 NumPy style array- Parameters:
model_dir (str | Path | None)
cache (AudioCache | None)
fallback_to_mock (bool)
- supported_voices: list[str] = ['af_alloy', 'af_aoede', 'af_bella', 'af_heart', 'af_jessica', 'af_kore', 'af_nicole', 'af_nova', 'af_river', 'af_sarah', 'af_sky', 'am_adam', 'am_echo', 'am_eric', 'am_fenrir', 'am_liam', 'am_michael', 'am_onyx', 'am_puck', 'am_santa', 'bf_alice', 'bf_emma', 'bf_isabella', 'bf_lily', 'bm_daniel', 'bm_fable', 'bm_george', 'bm_lewis', 'ef_dora', 'em_alex', 'em_santa', 'ff_siwis', 'hf_alpha', 'hf_beta', 'hm_omega', 'hm_psi', 'if_sara', 'im_nicola', 'jf_alpha', 'jf_gongitsune', 'jf_nezumi', 'jf_tebukuro', 'jm_kumo', 'pf_dora', 'pm_alex', 'pm_santa', 'zf_xiaobei', 'zf_xiaoni', 'zf_xiaoxiao', 'zf_xiaoyi', 'zm_yunjian', 'zm_yunxi', 'zm_yunxia', 'zm_yunyang']¶
- voice_catalog = {'american_female': ['af_alloy', 'af_aoede', 'af_bella', 'af_heart', 'af_jessica', 'af_kore', 'af_nicole', 'af_nova', 'af_river', 'af_sarah', 'af_sky'], 'american_male': ['am_adam', 'am_echo', 'am_eric', 'am_fenrir', 'am_liam', 'am_michael', 'am_onyx', 'am_puck', 'am_santa'], 'british_female': ['bf_alice', 'bf_emma', 'bf_isabella', 'bf_lily'], 'british_male': ['bm_daniel', 'bm_fable', 'bm_george', 'bm_lewis'], 'french': ['ff_siwis'], 'hindi': ['hf_alpha', 'hf_beta', 'hm_omega', 'hm_psi'], 'italian': ['if_sara', 'im_nicola'], 'japanese': ['jf_alpha', 'jf_gongitsune', 'jf_nezumi', 'jf_tebukuro', 'jm_kumo'], 'mandarin': ['zf_xiaobei', 'zf_xiaoni', 'zf_xiaoxiao', 'zf_xiaoyi', 'zm_yunjian', 'zm_yunxi', 'zm_yunxia', 'zm_yunyang'], 'portuguese': ['pf_dora', 'pm_alex', 'pm_santa'], 'spanish': ['ef_dora', 'em_alex', 'em_santa']}¶
- blend_presets = {'blend_host_female': 'af_aoede:0.6+af_kore:0.4', 'blend_indian_female': 'hf_alpha:0.55+af_aoede:0.45', 'blend_indian_male': 'hm_omega:0.55+am_liam:0.45', 'blend_professor': 'am_fenrir:0.55+am_onyx:0.45', 'blend_storyteller': 'bm_fable:0.6+am_liam:0.4', 'blend_transatlantic': 'am_puck:0.6+bm_fable:0.4', 'studio_host_f': 'af_aoede:0.6+af_kore:0.4', 'studio_indian_en': 'hm_omega:0.55+am_liam:0.45', 'studio_indian_f': 'hf_alpha:0.55+af_aoede:0.45', 'studio_professor': 'am_fenrir:0.55+am_onyx:0.45', 'studio_transatlantic': 'am_puck:0.6+bm_fable:0.4'}¶
- list_voices(category=None, include_blends=False)[source]¶
Return available Kokoro voice IDs.
- Parameters:
- Return type:
- classmethod parse_voice_spec(voice_spec, available_voices=None)[source]¶
Parse a voice name, blend expression, dict, or sequence into normalized
(voice_id, weight)pairs.Weights are normalized so that they sum to
1.0.
- classmethod format_voice_spec(voice_spec, available_voices=None)[source]¶
Convert any voice specification into a canonical string label for caching and metadata.
- classmethod infer_language(voice_spec, native_non_english=False)[source]¶
Infer espeak-ng phonemizer language code from the dominant voice in voice_spec.
By default (native_non_english=False), British voices (bf_*, bm_*) select “en-gb” and all other voices default to “en-us” so cross-accent voices (e.g. hm_omega, hf_alpha) speak English scripts seamlessly. When native_non_english=True, non-English prefixes map to their native espeak-ng language code (“es”, “fr-fr”, “hi”, “it”, “ja”, “pt-br”, “cmn”).
- blend_voices(voice_spec)[source]¶
Compute a blended (510, 1, 256) float32 style embedding from two or more Kokoro voices.
- Parameters:
voice_spec (str | Mapping[str, float] | Sequence[tuple[str, float] | str]) – A blend string (e.g.
"am_puck:0.6+bm_fable:0.4"or"am_puck+bm_fable"), preset name (e.g."blend_transatlantic"), dict{"am_puck": 0.6, "bm_fable": 0.4}, or sequence of(voice_name, weight)pairs.- Returns:
A
(510, 1, 256)float32 NumPy style vector suitable for passing tosynthesize(voice=...).- Return type:
- synthesize(text, voice=None, speed=1.0, instruct=None, output_path=None, lang=None, **kwargs)[source]¶
Synthesize text into speech and return an AudioClip with timestamps.
- Parameters:
text (str) – Text to speak.
voice (str | Mapping[str, float] | Sequence[tuple[str, float] | str] | ndarray | None) – Voice name or ID. If None, uses default_voice.
speed (float) – Speech rate multiplier (1.0 = normal).
instruct (str | None) – Natural language instruction for tone/prosody/emotion (used by Qwen3-TTS).
output_path (str | Path | None) – Optional explicit output WAV path. If None, writes to a temp or cache path.
**kwargs (Any) – Extra provider-specific parameters.
lang (str | None)
**kwargs
- Returns:
An AudioClip instance containing the path, duration, and word timestamps.
- Return type:
AWS Polly text-to-speech provider with native SpeechMarks word-level alignment.
- class voiceanim.providers.polly_provider.PollyProvider(engine='neural', region_name=None, cache=None)[source]¶
Bases:
BaseVoiceProviderAWS Polly text-to-speech provider.
Leverages AWS Polly Neural and Generative engines, and extracts native word-level and sentence-level SpeechMarks for precise whiteboard visual sync.
- Parameters:
engine (str)
region_name (str | None)
cache (AudioCache | None)
- supported_voices: list[str] = ['Matthew', 'Ruth', 'Joanna', 'Stephen', 'Danielle', 'Gregory', 'Amy', 'Olivia']¶
- synthesize(text, voice=None, speed=1.0, instruct=None, output_path=None, **kwargs)[source]¶
Synthesize text into speech and return an AudioClip with timestamps.
- Parameters:
text (str) – Text to speak.
voice (str | None) – Voice name or ID. If None, uses default_voice.
speed (float) – Speech rate multiplier (1.0 = normal).
instruct (str | None) – Natural language instruction for tone/prosody/emotion (used by Qwen3-TTS).
output_path (str | Path | None) – Optional explicit output WAV path. If None, writes to a temp or cache path.
**kwargs (Any) – Extra provider-specific parameters.
- Returns:
An AudioClip instance containing the path, duration, and word timestamps.
- Return type:
Qwen3-TTS provider with prompt-driven natural language instruction control.
Supports Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice and 0.6B models for multi-dimensional acoustic attribute control (timbre, emotion, rhythm, and prosody) via natural language instructions.
- class voiceanim.providers.qwen_provider.QwenTTSProvider(model_id='Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice', cache=None, hf_token=None, device='auto', fallback_to_mock=False)[source]¶
Bases:
BaseVoiceProviderQwen3-TTS model provider supporting natural language instruction prompts.
- Allows fine-grained, prompt-based control over emotion, prosody, and style:
engine.synthesize(”…”, instruct=”Speak with inquisitive warmth, pausing after questions”)
- Parameters:
model_id (str)
cache (AudioCache | None)
hf_token (str | None)
device (str)
fallback_to_mock (bool)
- synthesize(text, voice=None, speed=1.0, instruct=None, output_path=None, language='English', **kwargs)[source]¶
Synthesize text into speech and return an AudioClip with timestamps.
- Parameters:
text (str) – Text to speak.
voice (str | None) – Voice name or ID. If None, uses default_voice.
speed (float) – Speech rate multiplier (1.0 = normal).
instruct (str | None) – Natural language instruction for tone/prosody/emotion (used by Qwen3-TTS).
output_path (str | Path | None) – Optional explicit output WAV path. If None, writes to a temp or cache path.
**kwargs (Any) – Extra provider-specific parameters.
language (str)
**kwargs
- Returns:
An AudioClip instance containing the path, duration, and word timestamps.
- Return type:
Mock text-to-speech provider for zero-cost, offline testing and CI.
- class voiceanim.providers.mock_provider.MockVoiceProvider(cache=None, words_per_minute=160.0)[source]¶
Bases:
BaseVoiceProviderDeterministic mock provider that generates synthetic tone WAV files with word timestamps.
- Parameters:
cache (AudioCache | None)
words_per_minute (float)
- synthesize(text, voice=None, speed=1.0, instruct=None, output_path=None, **kwargs)[source]¶
Synthesize text into speech and return an AudioClip with timestamps.
- Parameters:
text (str) – Text to speak.
voice (str | None) – Voice name or ID. If None, uses default_voice.
speed (float) – Speech rate multiplier (1.0 = normal).
instruct (str | None) – Natural language instruction for tone/prosody/emotion (used by Qwen3-TTS).
output_path (str | Path | None) – Optional explicit output WAV path. If None, writes to a temp or cache path.
**kwargs (Any) – Extra provider-specific parameters.
- Returns:
An AudioClip instance containing the path, duration, and word timestamps.
- Return type: