voiceanim Package

Top-Level Facade (voiceanim)

voiceanim: Realistic speech synthesis, word-level alignment, and narration sync for handanim.

class voiceanim.VoiceEngine[source]

Bases: object

Unified 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:

BaseVoiceProvider

static list_providers()[source]

List all supported voice provider names.

Return type:

list[str]

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).

Parameters:
  • provider (str)

  • category (str | None)

  • include_blends (bool)

  • kwargs (Any)

Return type:

list[str]

classmethod blend_voices(voice_spec, **kwargs)[source]

Compute a blended (510, 1, 256) float32 style vector across two or more Kokoro voices.

Parameters:
  • voice_spec (Any)

  • kwargs (Any)

Return type:

Any

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:

AudioClip

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.

Parameters:
Return type:

list[NarrationBeat]

static align_clip(clip, backend='auto', model_size='base', language='en')[source]

Run forced alignment on an existing AudioClip to refresh its word timestamps.

Parameters:
Return type:

AudioClip

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.

Parameters:
Return type:

AudioClip

static generate_theme_music(duration, output_path=None, style='marimba', bpm=104.0, volume=0.22)[source]

Generate repeating open-source background theme music of length duration.

Parameters:
Return type:

AudioClip

static loop_audio(audio_source, duration, output_path=None, volume=0.22)[source]

Repeat an audio file, AudioClip, or built-in theme preset to match duration.

Parameters:
Return type:

AudioClip

class voiceanim.AudioClip(audio_path, duration, sample_rate=24000, text='', words=<factory>, sentences=<factory>, provider='', voice='', instruct=None, metadata=<factory>)[source]

Bases: object

Audio clip representation with speech marks, alignment timestamps, and metadata.

Parameters:
audio_path: str
duration: float
sample_rate: int = 24000
text: str = ''
words: list[WordTimestamp]
sentences: list[SentenceTimestamp]
provider: str = ''
voice: str = ''
instruct: str | None = None
metadata: dict
get_word_time(target_word, occurrence=1)[source]

Find the start timestamp in seconds of the N-th occurrence of a word.

Parameters:
  • target_word (str) – The word to find (case-insensitive, punctuation-stripped).

  • occurrence (int) – Which occurrence (1-based index). Defaults to 1 (first).

Returns:

Start time in seconds, or None if not found.

Return type:

float | None

get_word_range(target_word, occurrence=1)[source]

Find the (start, end) timestamp range of the N-th occurrence of a word.

Parameters:
  • target_word (str)

  • occurrence (int)

Return type:

tuple[float, float] | None

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.

Parameters:

output_path (str | Path | None)

Return type:

str

export_vtt(output_path=None)[source]

Export speech marks as WebVTT (.vtt) subtitle format.

Parameters:

output_path (str | Path | None)

Return type:

str

to_dict()[source]
Return type:

dict

classmethod from_dict(data)[source]
Parameters:

data (dict)

Return type:

AudioClip

save_json(json_path)[source]
Parameters:

json_path (str | Path)

classmethod load_json(json_path)[source]
Parameters:

json_path (str | Path)

Return type:

AudioClip

class voiceanim.WordTimestamp(word, start, end, confidence=1.0, speaker=None)[source]

Bases: object

Timestamp for an individual spoken word.

Parameters:
word: str
start: float
end: float
confidence: float = 1.0
speaker: str | None = None
property duration: float
to_dict()[source]
Return type:

dict

classmethod from_dict(data)[source]
Parameters:

data (dict)

Return type:

WordTimestamp

class voiceanim.SentenceTimestamp(text, start, end, words=<factory>, speaker=None)[source]

Bases: object

Timestamp for a sentence or complete phrase.

Parameters:
text: str
start: float
end: float
words: list[WordTimestamp]
speaker: str | None = None
property duration: float
to_dict()[source]
Return type:

dict

classmethod from_dict(data)[source]
Parameters:

data (dict)

Return type:

SentenceTimestamp

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: object

A designated beat or section in an animation narration script with optional delivery direction.

Parameters:
id: str
text: str
instruct: str | None = None
voice: str | None = None
provider: str | None = None
speed: float | None = None
exaggeration: float | None = None
cfg_weight: float | None = None
controls: dict[str, float] | None = None
ref_audio: str | None = None
start_time: float | None = None
target_duration: float | None = None
clip: AudioClip | None = None
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:

NarrationBeat

class voiceanim.AudioCache(cache_dir='.voiceanim_cache')[source]

Bases: object

Manages 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.

Parameters:
Return type:

str

get(key)[source]

Retrieve a cached AudioClip if both .wav and .json exist and are intact.

Parameters:

key (str)

Return type:

AudioClip | None

put(key, clip, audio_bytes=None, source_audio_path=None)[source]

Store an AudioClip and its waveform into the cache.

Parameters:
  • key (str) – The SHA-256 cache key.

  • clip (AudioClip) – AudioClip metadata.

  • audio_bytes (bytes | None) – Optional raw bytes of the audio (WAV/MP3).

  • source_audio_path (str | Path | None) – Optional path to an existing audio file to copy into cache.

Returns:

Updated AudioClip pointing to the cached audio file path.

Return type:

AudioClip

clear()[source]

Remove all files from the cache directory.

class voiceanim.ForcedAligner(backend='auto', model_size='base', language='en')[source]

Bases: object

Forced word-level aligner supporting neural Whisper backends and acoustic VAD fallback.

Parameters:
  • backend (str)

  • model_size (str)

  • language (str)

classmethod available_backends()[source]

Return list of currently importable alignment backends on this machine.

Return type:

list[str]

align(audio_path, text, duration=None)[source]

Align text to audio_path and return (word_timestamps, backend_used).

Parameters:
Return type:

tuple[list[WordTimestamp], str]

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.

Parameters:
Return type:

list[WordTimestamp]

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.

Parameters:
Return type:

AudioClip

class voiceanim.VoiceTimelineSync[source]

Bases: object

Utilities 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:

tuple[Any, Any]

static validate_beat_fit(beats)[source]

Check whether narration audio fits within designated animation timing slots.

Parameters:

beats (list[NarrationBeat])

Return type:

list[str]

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=None and resamples any mismatched clips.

Parameters:
Return type:

AudioClip

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.

  • audio_path (str | Path) – Path to source audio track.

  • output_path (str | Path) – Destination video path.

  • 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:

str

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:

str

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:

AudioClip

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:

AudioClip

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

Parameters:
Return type:

ndarray

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)

Parameters:
Return type:

ndarray

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

Parameters:
Return type:

ndarray

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

Parameters:
Return type:

ndarray

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).

Parameters:
Return type:

ndarray

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).

Parameters:
Return type:

ndarray

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).

Parameters:
Return type:

ndarray

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

Parameters:
Return type:

ndarray

class voiceanim.BaseVoiceProvider[source]

Bases: ABC

Abstract interface for a text-to-speech provider.

name: str = 'base'
default_voice: str = ''
supported_voices: list[str] = []
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:

AudioClip

list_voices()[source]

Return the list of supported voice IDs.

Return type:

list[str]

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:

list[WordTimestamp]

static extract_sentences(text, word_timings)[source]

Group word timestamps into sentence boundaries based on terminal punctuation.

Parameters:
Return type:

list[SentenceTimestamp]

static write_wav(file_path, samples, sample_rate=24000)[source]

Write 1D numpy array samples (float32 [-1, 1] or int16) to standard 16-bit PCM WAV.

Parameters:
Return type:

None

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: BaseVoiceProvider

Expressive speech synthesis provider backed by Resemble AI Chatterbox.

Parameters:
  • model_id (str | None)

  • backend (str)

  • device (str)

  • ref_audio (str | Path | None)

  • exaggeration (float | None)

  • cfg_weight (float | None)

  • temperature (float | None)

  • align_backend (str)

  • cache (AudioCache | None)

  • fallback_to_mock (bool)

name: str = 'chatterbox'
default_voice: str = 'default'
supported_voices: list[str] = ['default', 'energetic', 'dramatic', 'playful', 'calm', 'storyteller']
synthesize(text, voice=None, speed=1.0, instruct=None, output_path=None, *, ref_audio=None, exaggeration=None, cfg_weight=None, temperature=None, align='auto', **kwargs)[source]

Synthesize expressive speech with Chatterbox and compute word timestamps.

Parameters:
Return type:

AudioClip

class voiceanim.KokoroProvider(model_dir=None, cache=None, fallback_to_mock=False)[source]

Bases: BaseVoiceProvider

Local, 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:
name: str = 'kokoro'
default_voice: str = 'af_heart'
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:
  • category (str | None) – Optional category filter (e.g., "american_male", "american_female", "british_male", "british_female", "hindi", "spanish", "french", "italian", "japanese", "portuguese", "mandarin").

  • include_blends (bool) – If True, appends built-in named blend presets.

Return type:

list[str]

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.

Parameters:
Return type:

list[tuple[str, float]]

classmethod format_voice_spec(voice_spec, available_voices=None)[source]

Convert any voice specification into a canonical string label for caching and metadata.

Parameters:
Return type:

str

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”).

Parameters:
Return type:

str

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 to synthesize(voice=...).

Return type:

ndarray

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:

AudioClip

class voiceanim.PollyProvider(engine='neural', region_name=None, cache=None)[source]

Bases: BaseVoiceProvider

AWS 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:
name: str = 'polly'
default_voice: str = 'Matthew'
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:

AudioClip

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: BaseVoiceProvider

Qwen3-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:
name: str = 'qwen'
default_voice: str = 'Vivian'
supported_voices: list[str] = ['Vivian', 'Ryan', 'Uncle_Martin', 'Serena', 'Aiden']
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:

AudioClip

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: BaseVoiceProvider

Expressive speech synthesis provider backed by Zyphra ZONOS3-Mini.

Parameters:
  • model_id (str | None)

  • backend (str)

  • api_url (str | None)

  • device (str)

  • ref_audio (str | Path | None)

  • language (str)

  • align_backend (str)

  • cache (AudioCache | None)

  • fallback_to_mock (bool)

name: str = 'zonos'
default_voice: str = 'jett'
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.

Parameters:
Return type:

AudioClip

class voiceanim.MockVoiceProvider(cache=None, words_per_minute=160.0)[source]

Bases: BaseVoiceProvider

Deterministic mock provider that generates synthetic tone WAV files with word timestamps.

Parameters:
name: str = 'mock'
default_voice: str = 'mock_narrator'
supported_voices: list[str] = ['mock_narrator', 'mock_female', 'mock_male']
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:

AudioClip

voiceanim.get_provider(name='kokoro', **kwargs)[source]

Retrieve an initialized voice provider instance.

Parameters:
  • name (str) – Provider name (‘kokoro’ [default], ‘polly’, ‘qwen’, ‘chatterbox’, ‘zonos’, ‘mock’).

  • **kwargs (Any) – Provider-specific configuration arguments.

Returns:

An instance of BaseVoiceProvider.

Return type:

BaseVoiceProvider

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'
Parameters:

text (str)

Return type:

str

class voiceanim.DialogueTurn(speaker, text, voice=None, provider=None, speed=None, instruct=None, pause_after=None)[source]

Bases: object

A single spoken turn in a multi-speaker dialogue.

Parameters:
  • speaker (str)

  • text (str)

  • voice (str | None)

  • provider (str | None)

  • speed (float | None)

  • instruct (str | None)

  • pause_after (float | None)

speaker: str
text: str
voice: str | None = None
provider: str | None = None
speed: float | None = None
instruct: str | None = None
pause_after: float | None = None
class voiceanim.SpeakerProfile(name, voice='af_heart', provider='kokoro', speed=1.0, instruct=None, color=None, highlight=None)[source]

Bases: object

Voice and visual theme configuration for a dialogue participant.

Parameters:
name: str
voice: str = 'af_heart'
provider: str = 'kokoro'
speed: float = 1.0
instruct: str | None = None
color: tuple[float, float, float] | None = None
highlight: tuple[float, float, float] | None = None
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:

AudioClip

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: object

Timestamp for an individual spoken word.

Parameters:
word: str
start: float
end: float
confidence: float = 1.0
speaker: str | None = None
property duration: float
to_dict()[source]
Return type:

dict

classmethod from_dict(data)[source]
Parameters:

data (dict)

Return type:

WordTimestamp

class voiceanim.schema.SentenceTimestamp(text, start, end, words=<factory>, speaker=None)[source]

Bases: object

Timestamp for a sentence or complete phrase.

Parameters:
text: str
start: float
end: float
words: list[WordTimestamp]
speaker: str | None = None
property duration: float
to_dict()[source]
Return type:

dict

classmethod from_dict(data)[source]
Parameters:

data (dict)

Return type:

SentenceTimestamp

class voiceanim.schema.AudioClip(audio_path, duration, sample_rate=24000, text='', words=<factory>, sentences=<factory>, provider='', voice='', instruct=None, metadata=<factory>)[source]

Bases: object

Audio clip representation with speech marks, alignment timestamps, and metadata.

Parameters:
audio_path: str
duration: float
sample_rate: int = 24000
text: str = ''
words: list[WordTimestamp]
sentences: list[SentenceTimestamp]
provider: str = ''
voice: str = ''
instruct: str | None = None
metadata: dict
get_word_time(target_word, occurrence=1)[source]

Find the start timestamp in seconds of the N-th occurrence of a word.

Parameters:
  • target_word (str) – The word to find (case-insensitive, punctuation-stripped).

  • occurrence (int) – Which occurrence (1-based index). Defaults to 1 (first).

Returns:

Start time in seconds, or None if not found.

Return type:

float | None

get_word_range(target_word, occurrence=1)[source]

Find the (start, end) timestamp range of the N-th occurrence of a word.

Parameters:
  • target_word (str)

  • occurrence (int)

Return type:

tuple[float, float] | None

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.

Parameters:

output_path (str | Path | None)

Return type:

str

export_vtt(output_path=None)[source]

Export speech marks as WebVTT (.vtt) subtitle format.

Parameters:

output_path (str | Path | None)

Return type:

str

to_dict()[source]
Return type:

dict

classmethod from_dict(data)[source]
Parameters:

data (dict)

Return type:

AudioClip

save_json(json_path)[source]
Parameters:

json_path (str | Path)

classmethod load_json(json_path)[source]
Parameters:

json_path (str | Path)

Return type:

AudioClip

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: object

A designated beat or section in an animation narration script with optional delivery direction.

Parameters:
id: str
text: str
instruct: str | None = None
voice: str | None = None
provider: str | None = None
speed: float | None = None
exaggeration: float | None = None
cfg_weight: float | None = None
controls: dict[str, float] | None = None
ref_audio: str | None = None
start_time: float | None = None
target_duration: float | None = None
clip: AudioClip | None = None
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:

NarrationBeat

voiceanim.timeline

Animation timeline synchronization with spoken narration.

class voiceanim.timeline.VoiceTimelineSync[source]

Bases: object

Utilities 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:

tuple[Any, Any]

static validate_beat_fit(beats)[source]

Check whether narration audio fits within designated animation timing slots.

Parameters:

beats (list[NarrationBeat])

Return type:

list[str]

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=None and resamples any mismatched clips.

Parameters:
Return type:

AudioClip

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.

Parameters:
Return type:

str

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.

Parameters:
Return type:

str

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.

Parameters:
Return type:

ndarray

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

Parameters:
Return type:

ndarray

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)

Parameters:
Return type:

ndarray

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).

Parameters:
Return type:

ndarray

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).

Parameters:
Return type:

ndarray

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).

Parameters:
Return type:

ndarray

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

Parameters:
Return type:

ndarray

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

Parameters:
Return type:

ndarray

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

Parameters:
Return type:

ndarray

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.

Parameters:
Return type:

ndarray

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:

AudioClip

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:

AudioClip

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.

Parameters:
Return type:

float

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.

Parameters:
Return type:

ndarray

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:

str

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.

  • audio_path (str | Path) – Path to source audio track.

  • output_path (str | Path) – Destination video path.

  • 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:

str

voiceanim.cache

Content-addressed audio cache for deterministic and reproducible voice generation.

class voiceanim.cache.AudioCache(cache_dir='.voiceanim_cache')[source]

Bases: object

Manages 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.

Parameters:
Return type:

str

get(key)[source]

Retrieve a cached AudioClip if both .wav and .json exist and are intact.

Parameters:

key (str)

Return type:

AudioClip | None

put(key, clip, audio_bytes=None, source_audio_path=None)[source]

Store an AudioClip and its waveform into the cache.

Parameters:
  • key (str) – The SHA-256 cache key.

  • clip (AudioClip) – AudioClip metadata.

  • audio_bytes (bytes | None) – Optional raw bytes of the audio (WAV/MP3).

  • source_audio_path (str | Path | None) – Optional path to an existing audio file to copy into cache.

Returns:

Updated AudioClip pointing to the cached audio file path.

Return type:

AudioClip

clear()[source]

Remove all files from the cache directory.

voiceanim.providers

Abstract base class and utilities for speech synthesis providers.

class voiceanim.providers.base.BaseVoiceProvider[source]

Bases: ABC

Abstract interface for a text-to-speech provider.

name: str = 'base'
default_voice: str = ''
supported_voices: list[str] = []
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:

AudioClip

list_voices()[source]

Return the list of supported voice IDs.

Return type:

list[str]

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:

list[WordTimestamp]

static extract_sentences(text, word_timings)[source]

Group word timestamps into sentence boundaries based on terminal punctuation.

Parameters:
Return type:

list[SentenceTimestamp]

static write_wav(file_path, samples, sample_rate=24000)[source]

Write 1D numpy array samples (float32 [-1, 1] or int16) to standard 16-bit PCM WAV.

Parameters:
Return type:

None

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: BaseVoiceProvider

Local, 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:
name: str = 'kokoro'
default_voice: str = 'af_heart'
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:
  • category (str | None) – Optional category filter (e.g., "american_male", "american_female", "british_male", "british_female", "hindi", "spanish", "french", "italian", "japanese", "portuguese", "mandarin").

  • include_blends (bool) – If True, appends built-in named blend presets.

Return type:

list[str]

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.

Parameters:
Return type:

list[tuple[str, float]]

classmethod format_voice_spec(voice_spec, available_voices=None)[source]

Convert any voice specification into a canonical string label for caching and metadata.

Parameters:
Return type:

str

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”).

Parameters:
Return type:

str

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 to synthesize(voice=...).

Return type:

ndarray

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:

AudioClip

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: BaseVoiceProvider

AWS 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:
name: str = 'polly'
default_voice: str = 'Matthew'
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:

AudioClip

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: BaseVoiceProvider

Qwen3-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:
name: str = 'qwen'
default_voice: str = 'Vivian'
supported_voices: list[str] = ['Vivian', 'Ryan', 'Uncle_Martin', 'Serena', 'Aiden']
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:

AudioClip

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: BaseVoiceProvider

Deterministic mock provider that generates synthetic tone WAV files with word timestamps.

Parameters:
name: str = 'mock'
default_voice: str = 'mock_narrator'
supported_voices: list[str] = ['mock_narrator', 'mock_female', 'mock_male']
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:

AudioClip