an.audio#

Audio pipeline — TTS and lip-sync providers + orchestration.

Phase 3 ships:

  • Protocols: TTSProvider, LipSyncProvider (Phase 1).

  • Default offline provider: OfflineTTS (silent WAV). The lip-sync providers (OfflineLipSync deterministic char-to-viseme, RhubarbLipSync, WhisperLipSync) moved to cutan with the cut-out genre (an#225), and the old names were removed from here (an#321): import them from cutan.audio.

  • Real providers: ElevenLabsTTS (needs ELEVEN_API_KEY); RecordedTTS, a performer’s imported takes (an voices import, an.audio.recorded).

  • Orchestration: produce_audio_for_dialogue / produce_audio_for_scene walk a SceneIR, synthesize, persist to mall, stamp viseme tracks back onto the IR.

The defaults are intentionally offline so the entire an pipeline works without external services.

Functions

list_voices(provider, *[, api_key, search, make])

The voices provider offers, as rows (an#712): browse_voices() through VoiceMeta.as_row().

word_timings_to_visemes(words, *, ...[, ...])

Distribute viseme keyframes across word boundaries.

lipsync_cache_id(provider)

What a provider puts in a viseme track's content key (an.audio.pipeline.viseme_key()): its name, and its CACHE_VERSION_ATTR when it states one.

clip_timings(audio, field)

audio's words or phones as a list of (label, start_s, end_s); None when it has none (or its an predates the field).

phone_alphabet(phones)

"arpabet" when every phone is ARPAbet as aligners write it (ASCII, one case throughout, each in an's ARPABET_PHONES once its stress digit is dropped), else "ipa".

phone_viseme(phone, *[, alphabet])

The Rhubarb shape of one phone in alphabet; REST_VISEME for a silence; None for a phone the table does not know.

phones_to_visemes(phones, *, total_duration)

A viseme track from phone timings: each phone's shape at its start (in the clip's phone_alphabet()), the mouth closed at a silence, at a pause longer than min_gap_for_rest and after the last sound.

phones_track(audio, *[, phone_to_viseme, ...])

The mouth track of a clip whose phones are timed (AudioClip.phones, a take timed by a forced aligner, an#491), carrying the clip's words too; None when it has no phones, or one phone_to_viseme does not know.

import_recordings(project, audio, *[, ...])

Import a performer's recording(s) as the voice of their lines (an#490).

default_tts()

The default TTS provider: OfflineTTS.

default_lipsync()

The default lip-sync provider: the loaded genre's offline one (the deterministic char-to-viseme provider of cutan), else NullLipSync.

produce_audio_for_dialogue(dialogue[, mall, ...])

Synthesize audio + visemes for one dialogue line.

produce_audio_for_scene(scene[, mall, tts, ...])

Walk every dialogue line, synthesize, and stamp viseme tracks back.

speech_quote(scene, mall, *[, tts])

What speaking scene's dialogue would bill in dollars: 0.0 when every line is spoken by a provider that declares billed = False (offline, mac_say, recorded takes), else None: unknown, never free.

make_tts(name, *[, mall, api_key])

Instantiate a TTS provider by name.

make_lipsync(name, *[, language])

Instantiate a LipSync provider by name.

known_tts_names()

Return the registered TTS provider names.

known_lipsync_names()

Return the registered LipSync provider names.

Classes

TTSProvider(*args, **kwargs)

Text-to-speech provider.

AudioClip([path, bytes_, duration, ...])

A rendered audio clip, on disk or in memory.

VoiceMeta(voice_id, name, provider[, ...])

Metadata for a TTS voice as exposed by a provider.

VoiceRow

The keys of VoiceMeta.as_row(), typed for hosts (a plain dict at runtime); a test pins them to the dataclass.

LipSyncProvider(*args, **kwargs)

Audio + transcript → aligned viseme track.

Viseme(time, code[, intensity])

A single mouth-shape keyframe.

VisemeTrack([visemes, convention, duration, ...])

Aligned viseme sequence produced by a LipSyncProvider.

WordTimingProvider(*args, **kwargs)

Audio → [(word, start_s, end_s), ...].

NullLipSync()

The lip-sync provider of a core without a genre: no mouth shapes at all.

OfflineTTS(*[, sample_rate, channels, ...])

Default TTS provider: silent WAV of length proportional to text.

RecordedTTS(*[, recordings])

The recorded TTS provider: a line's audio is the take imported for it.

ElevenLabsTTS(*[, api_key, model_id, ...])

ElevenLabs-backed TTSProvider.

MacSayTTS(*[, default_voice_id, ...])

macOS say-backed TTSProvider.

class an.audio.AudioClip(path=None, bytes_=None, duration=0.0, sample_rate=44100, channels=1, voice_id=None, transcript=None, words=None, phones=None, phone_alphabet=None)[source]#

Bases: object

A rendered audio clip, on disk or in memory.

phone_alphabet: str | None#

The alphabet phones are in ("arpabet", "ipa"), as the take’s record states it (an#637, an#721); None when unknown, and a lip-sync provider then guesses from the labels (an#726).

phones: list[tuple[str, float, float]] | None#

The clip’s phone timings, (phone, start_s, end_s) from the clip’s start, when an aligner gave them (a TextGrid’s phones tier on a recorded take, an#491); None otherwise. A lip-sync provider that maps phones to mouth shapes can use them instead of spreading letters.

words: list[tuple[str, float, float]] | None#

The clip’s word timings — (word, start_s, end_s) from the clip’s start — when the provider knows them (a recorded take imported with a timed transcript: an.audio.recorded); None otherwise. A lip-sync provider that aligns from words prefers these to its own transcription, and the audio pipeline stamps them on the line.

class an.audio.ElevenLabsTTS(*, api_key=None, model_id='eleven_turbo_v2_5', output_format='mp3_44100_128', dialect=<function model_dialect>, native_break_s=<function model_native_break_s>, client_factory=None)[source]#

Bases: object

ElevenLabs-backed TTSProvider. Constructor takes an optional api_key (falls back to ELEVEN_API_KEY / ELEVENLABS_API_KEY).

Implements the TTSProvider protocol, plus the optional synthesis_options hook the audio pipeline reads (an#209).

billed: bool = True#

what may never run in memory).

Type:

Every request is charged (an#311

billed_characters(text, *, audio_tags=None, model_id=None, **_options)[source]#

Characters one request bills: the text as sent, audio tags included.

>>> tts = ElevenLabsTTS(api_key="unused")
>>> tts.billed_characters("Hi!", audio_tags=["excited"], model_id="eleven_v3")
13
Return type:

int

check_available()[source]#

Raise ElevenLabsUnavailableError when a request could not be sent (no API key) — what the audio pipeline asks before the first request of a render, so nothing is half-synthesized (an#305).

Return type:

None

client_factory#

api_key -> client; tests inject a fake so nothing reaches the API.

dialect#

how a model takes direction (voxy’s registry).

Type:

model_id -> Dialect

list_voices(*, search=None)[source]#

The account’s voices (its own plus the ones it saved), newest API.

search filters by name, description and labels on the server. An absent key or SDK yields []; a key that is present and a call that fails RAISES — an empty listing must mean “no voices”, not “it broke”.

Return type:

Iterable[VoiceMeta]

native_break_s#

the longest SSML break a model renders (voxy’s table).

Type:

model_id -> seconds

synthesis_options(voice, *, emotion=None, direction=None)[source]#

The synthesize keyword arguments a voice document and a line imply.

Only what is declared appears ({} for a plain voice), so the audio cache key — which includes this dict when it is non-empty — is unchanged for every voice that declares nothing new. audio_tags are the line’s [emotion] (unless neutral) then its direction cues, all of them on a model that reads tags. Elsewhere only the direction’s pause cues are kept (sent as SSML breaks, when the model renders a break that long: voxy’s table), any other direction cue is dropped with a warning, and the emotion stays a face-only cue, as before.

Return type:

dict[str, Any]

synthesize(text, voice_id=None, *, model_id=None, voice_settings=None, seed=None, audio_tags=None, **kw)[source]#

Speak text. The clip’s transcript is text WITHOUT the tags, so alignment and captions never read a cue.

Return type:

AudioClip

take_options(options, take)[source]#

The request for candidate take of a best-of-N line (an.audio.takes).

A declared seed is offset by the take, so a model that does honour it (every model but eleven_v3, measured) still returns different takes; without a seed the request is unchanged and the model’s own sampling varies the take.

>>> ElevenLabsTTS(api_key="unused").take_options({"seed": 11}, 2)
{'seed': 13}
Return type:

dict[str, Any]

class an.audio.LipSyncProvider(*args, **kwargs)[source]#

Bases: Protocol

Audio + transcript → aligned viseme track.

A provider that fills VisemeTrack.words also declares emits_word_timings = True (a plain class attribute, absent means False). The audio pipeline reads it to decide whether a line whose word_timings are missing needs re-alignment — without the flag, a provider that cannot supply words would re-align every line forever.

align(audio, transcript)[source]#

Produce a viseme track for audio given its transcript.

Return type:

VisemeTrack

class an.audio.MacSayTTS(*, default_voice_id='Samantha', sample_rate=22050, rate_wpm=None)[source]#

Bases: object

macOS say-backed TTSProvider.

Implements the TTSProvider protocol. Audible, deterministic, and fully offline — uses Apple’s voice synthesis bundled with the OS.

billed: bool = False#

an#311).

Type:

Costs nothing per request (stated, never inferred

repeatable: bool = True#

The same request gives the same audio, so best-of-N takes never apply (an.audio.takes.voice_takes()) and nothing is billed.

class an.audio.NullLipSync[source]#

Bases: object

The lip-sync provider of a core without a genre: no mouth shapes at all.

A genre that animates mouths (cutan) registers real providers (offline, rhubarb, whisper); without one, a line’s audio is still synthesized and the track it gets is empty – nothing draws a mouth anyway.

>>> NullLipSync().align(AudioClip(bytes_=b"", duration=0.5), "hi").duration
0.5
repeatable: bool = True#

a reader of the cache keys may run it in memory (an#311).

Type:

The same request gives the same track, and nothing is billed

class an.audio.OfflineTTS(*, sample_rate=22050, channels=1, seconds_per_char=0.06)[source]#

Bases: object

Default TTS provider: silent WAV of length proportional to text.

Implements the TTSProvider protocol.

billed: bool = False#

an#311).

Type:

Costs nothing per request (stated, never inferred

repeatable: bool = True#

The same request gives the same audio, so best-of-N takes never apply (an.audio.takes.voice_takes()) and nothing is billed.

silent: bool = True#

a line it speaks for a voice written for a real provider is a stand-in the render says so loudly (an#305).

Type:

Its audio is silence

class an.audio.RecordedTTS(*, recordings=None)[source]#

Bases: object

The recorded TTS provider: a line’s audio is the take imported for it.

Built by an.audio.providers.make_tts() with the project mall, so it reads mall["recordings"]; the pipeline hands it each line’s text and voice through synthesis_options() (which keys the line by its take’s digest) and synthesize(). A line with no take raises RecordingMissingError before anything else is touched — a recorded voice never falls back to a synthesized one.

>>> RecordedTTS().check_available()
Traceback (most recent call last):
    ...
an.audio.recorded.RecordedVoicesError: the recorded provider has no recordings store ...
list_voices()[source]#

One entry per voice that has takes in the store.

Return type:

list[VoiceMeta]

repeatable: bool = True#

The same request gives the same bytes, and nothing is billed (an#311).

synthesis_options(voice_doc, *, emotion=None, direction=None, text=None, voice_id=None)[source]#

{"recording": <digest>} of the take this line has — the audio key follows the take, so a re-recorded line is new audio. A take with phones adds {"timings": <digest>} of its words, phones (an#491) and their alphabet when stored (an#759): the same audio imported again with new timings is new audio to the caches, so the lip-sync sees them. (Only then: a take without phones keys as before.)

A line with no take is refused HERE, when the pipeline resolves every line’s request before the first synthesis: nothing of the scene is produced for a recorded voice that is missing a take. Without a line (an validate asks about the voice alone) there is nothing to refuse.

Return type:

dict[str, Any]

synthesize(text, voice_id='default', *, recording=None, **kw)[source]#

The take of text in voice_id (by recording digest when given), with its words.

Return type:

AudioClip

timings_for_clip(clip)[source]#

What the take whose bytes clip carries stored beside its audio: words, phones (an#491) and the phones’ phone_alphabet (an#726), each only when stored; {} for bytes of no take. One lookup, so the phones and their alphabet come from the same record.

Return type:

dict[str, Any]

class an.audio.TTSProvider(*args, **kwargs)[source]#

Bases: Protocol

Text-to-speech provider.

list_voices()[source]#

Return all voices the provider exposes.

Return type:

Iterable[VoiceMeta]

synthesize(text, voice_id, **kw)[source]#

Render text in voice_id’s voice. Returns an AudioClip.

Return type:

AudioClip

class an.audio.Viseme(time, code, intensity=1.0)[source]#

Bases: object

A single mouth-shape keyframe.

class an.audio.VisemeTrack(visemes=list(), convention='rhubarb', duration=0.0, words=None)[source]#

Bases: object

Aligned viseme sequence produced by a LipSyncProvider.

words carries the word timings the provider aligned from, when it had any (whisper, WordTimingsLipSync); None for providers that never see words (offline, Rhubarb — whose JSON is mouth cues only). Retained since an#96 rather than discarded after the viseme conversion: captions (Wave 8) and any consumer that wants to know which word a mouth shape belongs to read them from the IR.

class an.audio.VoiceMeta(voice_id, name, provider, language='en', gender=None, extra=dict(), is_stock=None, accent=None, description=None, preview_url=None)[source]#

Bases: object

Metadata for a TTS voice as exposed by a provider.

The fields are the provider-neutral facts a host shows and filters on (an#712): is_stock is the provider’s own answer to “nobody designed this” — one of its stock voices (ElevenLabs’ premade voices, a system voice) rather than one an account designed, cloned, recorded or added from a shared voice library; accent, description and preview_url (a sample to hear before casting, an#666) are None where the provider has none, and is_stock is None where it does not say.

extra is the provider’s own detail, in its own words. Keys hosts read (a contract): ElevenLabs’s category and labels. Its description and preview_url keys repeat the fields for one more cycle (hosts read extra["preview_url"] since an#666): read the fields.

as_row() is the flat, JSON-ready view a host lists (an.audio.list_voices()).

>>> VoiceMeta("v1", "Rachel", "elevenlabs", is_stock=True, accent="american",
...     extra={"category": "premade", "labels": {"age": "young"}}).as_row()
...
{'voice_id': 'v1', 'name': 'Rachel', 'provider': 'elevenlabs',
 'language': 'en', 'gender': None, 'is_stock': True, 'accent': 'american',
 'description': None, 'preview_url': None, 'category': 'premade'}
as_row()[source]#

The voice as one flat, JSON-ready row: every field but extra, plus the provider’s own category word (kept for display; filter on is_stock).

Return type:

dict[str, Any]

class an.audio.VoiceRow[source]#

Bases: TypedDict

The keys of VoiceMeta.as_row(), typed for hosts (a plain dict at runtime); a test pins them to the dataclass.

class an.audio.WordTimingProvider(*args, **kwargs)[source]#

Bases: Protocol

Audio → [(word, start_s, end_s), ...].

Implementations may run a transcriber (Whisper / Scribe) or look up pre-computed timings (muvid’s lacing store). Returned tuples are expected to be in ascending start-time order; gaps between words are fine and represent silence the lipsync provider should rest through.

words_for(audio, *, transcript='')[source]#

Return the word timings for audio.

Return type:

Sequence[tuple[str, float, float]]

an.audio.clip_timings(audio, field)[source]#

audio’s words or phones as a list of (label, start_s, end_s); None when it has none (or its an predates the field).

>>> clip_timings(AudioClip(duration=1.0, phones=[("M", 0, 0.1)]), "phones")
[('M', 0.0, 0.1)]
>>> clip_timings(AudioClip(duration=1.0), "phones") is None
True
Return type:

Optional[list[tuple[str, float, float]]]

an.audio.default_lipsync()[source]#

The default lip-sync provider: the loaded genre’s offline one (the deterministic char-to-viseme provider of cutan), else NullLipSync.

>>> default_lipsync().name in {"offline", "none"}
True
Return type:

LipSyncProvider

an.audio.default_tts()[source]#

The default TTS provider: OfflineTTS.

Return type:

TTSProvider

an.audio.import_recordings(project, audio, *, transcript=None, speaker=None, speakers=None, shot=None, voice=None, denoise=None, license=None, recorded_by=None, transcribe=None, transcriber=None, diarize=False, align=None, rough_timing=True, overlap_tolerance_s=0.05, match_threshold=0.75, write=True, scene_file='scene.md')[source]#

Import a performer’s recording(s) as the voice of their lines (an#490).

audio names the takes (a file, several, a directory, a glob): a whole take holding several lines, or one file per line. transcript is optional: SRT, WebVTT, TextGrid or word JSON time the lines so nothing is transcribed; a plain transcript (speaker: text lines) pairs one line per file, or is timed against transcribe’s words for a whole take; with no transcript at all the take is transcribed and its segments are the lines.

Each line is cut out, matched to the scene’s dialogue by its words (match_threshold), stored in mall["recordings"] with its provenance (license is required: the code you vouch for; recorded_by names the performer), and the speaker’s character is bound to a recorded voice document (voice, default <speaker>_recorded). Takes matching no line are added to shot (or the first shot of a scene with no dialogue). The gap heard between two lines of one file becomes the later line’s pause.

denoise ("afftdn" / "anlmdn") cleans each file first, through ffmpeg. transcribe is the transcriber seam (path -> segments); its default is scribed_transcriber() with transcriber as the backend and diarize for speaker labels, built only when a take needs it. align is the forced-aligner seam ((path, text) -> segments, e.g. mfa_aligner(), an#637): with a plain transcript it times the lines instead of a transcriber, and gives their phones, as a TextGrid would. Several lines in one take are first timed roughly by the transcriber (transcribe, else transcriber: a billed backend named there is billed for this pass too), and each is aligned within its own interval (an#716); rough_timing=False never transcribes and aligns the whole text as one utterance, which drifts on a long take. With no transcriber to run, the import falls back to that one utterance, with a RecordedVoicesWarning. Two lines of a take overlapping by more than overlap_tolerance_s seconds are refused, naming both (an#739): two voices at once cannot be cut apart. write=False runs everything but writes nothing (a dry run). scene_file imports into another scene of the project (scene.studio.md, an#554).

Return type:

ImportReport

an.audio.known_lipsync_names()[source]#

Return the registered LipSync provider names.

Return type:

list[str]

an.audio.known_tts_names()[source]#

Return the registered TTS provider names.

Return type:

list[str]

an.audio.lipsync_cache_id(provider)[source]#

What a provider puts in a viseme track’s content key (an.audio.pipeline.viseme_key()): its name, and its CACHE_VERSION_ATTR when it states one.

>>> class Offline:
...     name = "offline"
>>> lipsync_cache_id(Offline())
'offline'
>>> Offline.cache_version = "phones-1"
>>> lipsync_cache_id(Offline())
'offline@phones-1'
Return type:

str

an.audio.list_voices(provider, *, api_key=None, search=None, make=<function make_tts>)[source]#

The voices provider offers, as rows (an#712): browse_voices() through VoiceMeta.as_row().

api_key is a host’s own key for a provider that takes one (an.audio.providers.listable_providers()); None means the environment’s key, and "" is refused (ValueError), so a host that forwards a guest’s absent key never lists the server’s own account. A provider that cannot be asked at all (its check_available() fails: no key anywhere) raises its own typed error (ElevenLabs: ElevenLabsUnavailableError) rather than answering [], so an empty listing means “no voices”. search and make are as in browse_voices(). An unknown provider is a ValueError naming the known ones.

Return type:

list[VoiceRow]

an.audio.make_lipsync(name, *, language='en')[source]#

Instantiate a LipSync provider by name.

language (BCP-47) reaches providers that select behaviour by language — Rhubarb’s recognizer today; a future aligner’s weight allowlist.

The default name ("offline") resolves to NullLipSync when no loaded genre provides it, so voicing a line needs no genre; any other name that nothing provides is an error that says how to get it.

>>> make_lipsync("offline").name in {"offline", "none"}
True
Return type:

LipSyncProvider

an.audio.make_tts(name, *, mall=None, api_key=None)[source]#

Instantiate a TTS provider by name.

mall (the project mall) reaches the factories that take it — the recorded provider reads the project’s recordings store; api_key (a host’s own key) reaches those that take one (ElevenLabs, an#712); the others are built as before. Raises ValueError for unknown names with a list of known options.

>>> make_tts("recorded").name
'recorded'
Return type:

TTSProvider

an.audio.phone_alphabet(phones)[source]#

"arpabet" when every phone is ARPAbet as aligners write it (ASCII, one case throughout, each in an’s ARPABET_PHONES once its stress digit is dropped), else "ipa". Decided per clip: a SAMPA V (the vowel of love) beside a lowercase l is not ARPAbet V. The rule is an’s (phone_alphabet_of()), which says None where it cannot tell; this lip-sync reads that as IPA.

>>> phone_alphabet(["HH", "AH0", "L"]), phone_alphabet(["hh", "ah0"])
('arpabet', 'arpabet')
>>> phone_alphabet(["l", "V", "v"]), phone_alphabet(["h", "ə", "l"])
('ipa', 'ipa')
Return type:

str

an.audio.phone_viseme(phone, *, alphabet='arpabet')[source]#

The Rhubarb shape of one phone in alphabet; REST_VISEME for a silence; None for a phone the table does not know.

>>> phone_viseme("AA1"), phone_viseme("M"), phone_viseme("sil"), phone_viseme("Q9")
('D', 'A', 'X', None)
>>> [phone_viseme(p, alphabet="ipa") for p in ("tʃ", "iː", "əw", "ʘ")]
['B', 'B', 'F', None]
Return type:

Optional[str]

an.audio.phones_to_visemes(phones, *, total_duration, words=(), phone_to_viseme=<function phone_viseme>, char_to_viseme=None, rest_viseme='X', min_gap_for_rest=0.2, alphabet=None, intensity_of={}, takes_next_shape=frozenset({'HH', 'h', 'ɦ'}))[source]#

A viseme track from phone timings: each phone’s shape at its start (in the clip’s phone_alphabet()), the mouth closed at a silence, at a pause longer than min_gap_for_rest and after the last sound. A word of words with no phone under it is spoken by its letters (char_to_viseme).

alphabet is the take’s recorded one (AudioClip.phone_alphabet); with none, the clip’s labels decide (phone_alphabet()).

intensity_of maps a phone (its base: stress and modifiers dropped) to the Viseme.intensity of its cue, so a genre’s co-articulation can let a vowel’s B beat a tongue-only consonant’s (cutan#157). A phone of takes_next_shape (HH) shows the shape of the next spoken phone, kept as its own only at the end.

None when a phone is one phone_to_viseme does not know: a phone set this table was not written for is better spread by its words than guessed.

>>> phones_to_visemes([("ʘ", 0.0, 0.1)], total_duration=1.0) is None
True
>>> [(v.time, v.code) for v in phones_to_visemes(
...     [("M", 0.0, 0.1), ("AA1", 0.1, 0.3), ("P", 0.6, 0.7)], total_duration=0.7)]
[(0.0, 'X'), (0.0, 'A'), (0.1, 'D'), (0.3, 'X'), (0.6, 'A'), (0.7, 'X')]
Return type:

Optional[list[Viseme]]

an.audio.phones_track(audio, *, phone_to_viseme=<function phone_viseme>, char_to_viseme=None, rest_viseme='X', convention='rhubarb', intensity_of={})[source]#

The mouth track of a clip whose phones are timed (AudioClip.phones, a take timed by a forced aligner, an#491), carrying the clip’s words too; None when it has no phones, or one phone_to_viseme does not know.

>>> clip = AudioClip(duration=0.5, phones=[("M", 0.1, 0.2)], words=[("m", 0.1, 0.2)])
>>> track = phones_track(clip)
>>> [v.code for v in track.visemes], track.words
(['X', 'A', 'X', 'X'], [('m', 0.1, 0.2)])
>>> phones_track(AudioClip(duration=0.5)) is None
True
Return type:

Optional[VisemeTrack]

an.audio.produce_audio_for_dialogue(dialogue, mall=None, *, tts=None, lipsync=None, effects=None, voice_id=None, takes=<object object>, take_scorer=<function make_take_scorer>)[source]#

Synthesize audio + visemes for one dialogue line.

Side effects: when mall is provided, persists the WAV to mall["audio"] keyed by the content-hash of the dialogue, and persists the viseme JSON to mall["visemes"] similarly. Cache-friendly: a second call with identical inputs returns the cached versions.

effects (default: what the line’s voice declares in mall["voices"]) is applied to the synthesized audio BEFORE alignment, so the visemes are computed on the audio the viewer hears. The raw synthesis stays cached under its own key, so changing an effect never re-pays the TTS.

tts (default: the provider the voice document declares, else offline — tts_chooser()) is an override when given.

voice_id (default: the line’s voice_ref, else "default") is the voices-store key; produce_audio_for_scene() passes the one an.audio.voices.line_voice_id() resolves, so a character’s bound voice reaches here (an#194). The provider is handed the voice document’s own voice id when it names one.

What the provider’s optional synthesis_options hook derives from the voice document and the line (ElevenLabs: model_id, voice_settings, seed, and the [emotion]/direction audio tags — an#209) is passed to synthesize and keyed; the text handed to alignment is always the bare dialogue.text, never the tagged one.

takes (default: what the voice declares for this line — see an.audio.takes; None forces one take) synthesizes several takes, scores each with take_scorer(spec) on the audio the viewer hears, keeps the best and records the choice in mall["takes"]. A recorded choice is restored from the record and never re-rolled; a recorded take whose audio is gone raises TakeLostError before any request.

Return type:

tuple[AudioClip, VisemeTrack]

an.audio.produce_audio_for_scene(scene, mall=None, *, tts=None, lipsync=None, take_scorer=<function make_take_scorer>, announce=<function _announce_to_stderr>, overruns=True, strict=False, tts_factory=None)[source]#

Walk every dialogue line, synthesize, and stamp viseme tracks back.

Mutates the scene in place AND returns it (for chaining). Stamps Dialogue.duration, Dialogue.viseme_track, and Dialogue.audio_ref (mall[“audio”] key) so the renderer can find the audio later. Lines with an existing viseme_track AND audio_ref are not re-synthesized (idempotent).

Dialogue.start is DERIVED on every pass, synthesized or not, by Dialogue.planned_start(): the line’s at if set, else the previous line’s end plus its pause (an#187). So editing a pause re-times the shot without touching the audio, and every consumer of start — the mux, the visemes, captions, ducking — follows. A start on a line that was never synthesized is an authored start from before at existed, and is kept as the line’s at.

Every line’s request is resolved BEFORE anything is synthesized, so a malformed voice (an effect, a takes), a corrupt takes record or a recorded take whose audio is gone fails before a credit is spent; and announce (default: a line on stderr; None for silence) is told, before the first request, what best-of-N takes will bill (requests and the provider’s characters) and which recorded takes were chosen by an older scorer version than the current one (they are kept). After synthesis, a line that ends past its shot’s end (dialogue_overruns()) is announced too — or, with announce=None, a DialogueOverrunWarning — unless overruns=False: an render passes that, because it reports every post-synthesis finding together in its summary (an#254).

Who speaks each line (an#305, tts_chooser()): with tts not given (None, "" or VOICE_TTS), the line’s voice document’s provider, built by tts_factory (default an.audio.providers.make_tts()), else offline; a tts given speaks every line. A line spoken by another provider than its voice declares is a VoiceStandInWarning — the silent offline voice says so — and, with strict, a VoiceStandInError before any request. A voice written in words (notes) that nobody is recorded as choosing is a VoiceNotChosenWarning and, with strict, a VoiceNotChosenError before any request (an#486); a voice marked provisional is spoken and listed (VoiceProvisionalWarning). A provider with requests to send is asked check_available() first (ElevenLabs: is there a key?), and what a provider that bills per character will bill is announced before the first request — whatever chose the provider; a cached line is never billed and never counted.

Return type:

SceneIR

an.audio.speech_quote(scene, mall, *, tts=None)[source]#

What speaking scene’s dialogue would bill in dollars: 0.0 when every line is spoken by a provider that declares billed = False (offline, mac_say, recorded takes), else None: unknown, never free.

Each line’s provider is chosen as the render chooses it (tts_chooser(): tts overrides every voice, else each voice’s own document), so a voice the scene never speaks does not count. A provider that does not declare billed counts as billed. A billed provider is None even when its lines are cached: an counts billed characters (takes_cost_message()) but prices none in dollars yet; that rate is what turns None into a figure.

>>> from types import SimpleNamespace as NS
>>> shot = NS(entities=(), dialogue=[NS(voice_ref="bob", speaker="bob", text="Hi")])
>>> scene = NS(timeline=[shot])
>>> speech_quote(scene, {"voices": {"bob": {"provider": "offline"}}})
0.0
>>> speech_quote(scene, {"voices": {"bob": {"provider": "elevenlabs"}}}) is None
True
>>> speech_quote(scene, {"voices": {"bob": {"provider": "elevenlabs"}}}, tts="offline")
0.0
Return type:

float | None

an.audio.word_timings_to_visemes(words, *, total_duration, char_to_viseme, rest_viseme='X', min_gap_for_rest=0.2)[source]#

Distribute viseme keyframes across word boundaries.

Used by WhisperLipSync and WordTimingsLipSync. The algorithm: per word, walk its characters in order, look up each character’s viseme code, dedupe consecutive identical codes, and space the resulting keyframes evenly across the word’s [start, end] interval. In gaps wider than min_gap_for_rest — between two words, or after the last one before total_duration — insert a single rest keyframe just after the previous word ended.

Times are clamped to [0, total_duration] since some transcribers occasionally round the last word’s end past the audio’s actual length.

Return type:

list[Viseme]

Modules

cli

an voices ... — browse a TTS provider's voices from the shell (an#209).

effects

Voice effects: a deterministic transform applied to a synthesized line (an#163).

elevenlabs_tts

ElevenLabsTTS — real speech via the ElevenLabs API.

lipsync

Lip-sync provider protocol + viseme dataclasses.

loudness

Voice loudness: one integrated loudness for every voice of a film (an#315).

mac_say_tts

MacSayTTS — audible offline speech via macOS's built-in say command.

offline_tts

OfflineTTS — produces silent audio of plausible duration.

phones

Phones to mouth shapes: an aligner's phone timings as a Rhubarb viseme track (an#727).

pipeline

Audio pipeline orchestration: dialogue → audio → visemes → IR mutation.

providers

Provider factory: name → concrete TTS/LipSync provider instance.

recorded

Recorded voices: a performer's takes as the voice of a character (an#490).

shared_mixing

The fleet's shared audio component, mixing, as an imports it.

takes

Best-of-N takes: re-roll a line, score every take, keep the best, record the choice.

transcripts

Transcripts as INPUT: SRT, WebVTT, Praat TextGrid, word-timed JSON and plain text read into timed segments, and a known text matched to a transcriber's words.

tts

TTS provider protocol + supporting dataclasses.

voice_design

Design a project's voices from their written notes, then let the writer choose.

voice_listing

The voices a TTS provider offers, as rows a host can show and filter (an#712).

voices

Which voice speaks a dialogue line: the character → voice binding (an#194).