KingCobra's standard library includes std.tts, a native, dependency-free English speech synthesizer. There is no network, no downloaded voices and no operating-system speech service: it's C code inside the interpreter, it runs offline, and the same text, options and seed always produce the same samples, byte for byte. I've written a book-length guide to it, "Speech in KingCobra: The Complete Guide to std.tts" (first edition, November 2026, for KingCobra 1.0.0), and this post is the short version.
Read the guide (PDF, 45 pages):
https://github.com/DivyanshuSinha136/KingCobra/blob/main/tutorial/KingCobra_std_tts_Complete_Guide.pdf
Speech to a WAV file in one line
import std.tts;
fn main() {
let r = tts.to_wav("Hello! KingCobra can read $5.50, 10/28/2026 and 3:30 pm.", "hello.wav", "voice=narrator");
print(r.path, r.seconds, r.frames, r.bytes);
}
to_wav writes a 16-bit mono WAV at 22,050 Hz and returns the path, the length in seconds, the frame count and the file size. The first thing the engine does is turn that text into words, and you can see exactly what it will say before you listen:
print(tts.normalize("Dr. Smith paid $5.50 on 10/28/2026 at 3:30 pm for 4.5GB."));
doctor Smith paid five dollars and fifty cents on October twenty eighth twenty twenty six at three thirty P M for four point five gigabytes.
The idea: look before you listen
std.tts is a pipeline, and each stage can be inspected on its own:
text → clean-up → normalise → tokenise → pronounce → plan prosody → formant synthesizer → audio
(normalize) (words) (phonemes) (align)
That's the main design rule of the guide. A sentence that sounds wrong can almost always be diagnosed in text: normalize shows the words, phonemes and explain show the pronunciation and which rule produced it, words shows how tags were understood and align shows the timeline. You listen last.
Architecture: a classic pipeline, written from scratch in C
std.tts isn't a wrapper around someone else's speech engine. It's a small, classic text-to-speech pipeline written from scratch in about 3,600 lines of C and linked into the interpreter. Each stage lives in its own source file and hands a plain data structure to the next one, which is why every stage can be inspected from KingCobra.
| Stage | Source file (std/tts/) |
What it does | Inspect it with |
|---|---|---|---|
| Front end | tts_text.c |
Unicode clean-up, normalisation (numbers, years, dates, times, currency, units, abbreviations, URLs, camelCase), the SSML subset, inline {phonemes}, and the tokeniser |
normalize, words
|
| Pronunciation |
tts_g2p.c, tts_dict.c
|
The seven-step word path (homographs, lexicon, dictionary, morphology, compounds, acronyms, letter-to-sound rules) plus stress assignment |
phonemes, explain
|
| Phonemes and voices | tts_phon.c |
The 41-symbol inventory, articulatory parameters, ARPAbet and IPA conversion, and the built-in voices |
phoneme_table, voice_info
|
| Styles | tts_style.c |
The 20-parameter styles, tags, sound events and interjections, with typo correction |
styles, style_info, resolve_tag
|
| Planning | tts_plan.c |
Phone durations, articulatory segments and the pitch contour |
duration, align
|
| Synthesis | tts_synth.c |
The formant synthesizer that turns the plan into samples |
speak, to_wav
|
| Glue |
tts.c, tts_internal.h
|
The entry points, option parsing, and the structures shared between stages | info |
Here is one sentence followed through those stages, with the real output at each step:
text Dr. Smith paid $5.50 [sigh] today.
normalize doctor Smith paid five dollars and fifty cents today.
phonemes D AA1 K T ER0 | S M IH1 TH | P EY1 D | F AY1 V | D AA1 L ER0 Z | AE1 N D | F IH1 F T IY0 | S EH1 N T S | T AH0 D EY1 .
align doctor 0.04-0.414 · smith 0.414-0.731 · paid 0.731-1.063 · five 1.063-1.417 · dollars 1.417-1.851
and 1.851-2.006 · fifty 2.006-2.413 · cents 2.413-2.854 · [sigh] 2.854-3.864 · today 3.864-4.308
audio 100,073 frames, 4.538 s
The normalize and phonemes lines were run on the sentence without its tag, because normalize shows only the text stage and doesn't interpret [tags]. align is where the [sigh] shows up, as a one-second event in the timeline.
How the planner decides what it sounds like
The planner (tts_plan.c) turns phonemes into timed articulatory segments and a pitch contour. Grammatical words such as the, of and can are reduced and shortened, and content words carry the pitch accents on their stressed syllable. Durations follow Klatt-style rules: stress, consonant clusters, shortening before voiceless consonants and phrase-final lengthening. Pitch follows a declining baseline with accent peaks, so statements fall, yes/no questions rise, and commas give a continuation rise. Stops are built as closure, burst and aspiration, and US flapping or UK r-dropping is applied here, which is why the phoneme string doesn't depend on accent and the accent only appears at synthesis time.
How the synthesizer makes the sound
tts_synth.c is a Klatt-style formant synthesizer:
- Voicing: a Rosenberg glottal pulse, shaped by open quotient, spectral tilt, jitter, shimmer and breathiness.
- Vocal tract: a cascade of five formant resonators (F1 to F5) plus a nasal pole and zero pair.
- Noise: aspiration goes through the same cascade, while frication and stop bursts go through a parallel band-pass filter. Voiced fricatives are modulated by the glottal cycle, and a whisper replaces voicing with aspiration.
- Control: the planner's segments become piecewise-linear parameter tracks that are evaluated every 2 ms. Formant tracks coarticulate across phone boundaries, and stops glide from their place into the next vowel.
The formant values come from the classic Peterson and Barney / Klatt (1980) averages for an adult male, and the other voices scale them. That's what the tract parameter in define_voice does: it multiplies the formants, so a longer tract gives a larger, lower-sounding speaker.
Why it's built this way
- Every boundary is observable. A stage's output is a plain structure (words, phones, segments), so there is a function to look at it. You debug in text and listen last.
- It's deterministic. The only randomness is the noise and jitter, which come from one seeded generator, so the same text, options and seed give the same samples.
- Nothing is outside the module. No network, no voice files and no operating-system speech service, which makes the output the same on every platform.
-
The output is just audio. The result is a
std.music_notebuffer, so filters, reverb and mixing come for free.
What the guide covers
The guide has three parts and three appendices:
Part I: Meet std.tts
-
Design and conventions: the pipeline, determinism, the rules for options, errors and audio buffers, and a short list of what
std.ttsis not. -
Speaking:
speak,to_wav,say,save_wav, file sizes and sample rates, and the seed.
Part II: Controlling the voice
- Options reference: every option with its default and valid range (voice, rate, wpm, pitch, range, sr, pause, accent, reverb and more), plus measurements of what each really does to the timing.
- Text normalisation: numbers, money, dates, units, times, abbreviations and identifiers.
- Pronunciation: how a word's phonemes are chosen, and how to fix one.
- Vocal styles and expressive tags.
- Voices.
- SSML.
Part III: Timing, mixing and practice
- Timing, subtitles and lip-sync.
- Mixing with
std.music_note. - A complete program that builds an SRT subtitle file.
- Performance and limits.
- Common mistakes.
- A verification checklist for speech code.
- Work problems, with answers only.
Appendices: a cheat sheet, reference tables (functions grouped by purpose, the built-in voices, the 41-symbol phoneme set and style parameter ranges), and a map of the pipeline in the source tree. Boxes marked Gotcha, Measured, Expert tip and Note carry the non-obvious material.
Pronunciation you can debug
For each word the engine tries, in order, homograph rules, your lexicon, the built-in 1,215-word dictionary, morphology, compound splitting, acronym spelling, and about 330 letter-to-sound rules. explain tells you which one fired:
tts.add_word("kobold", "K OW1 B OW0 L D");
print(tts.explain("kobold").source); // lexicon
print(tts.explain("kobolds").source); // morphology
print(tts.explain("kobolds").phonemes); // K OW1 B OW0 L D Z
One add_word covers every inflection, because morphology builds on the lexicon. Homographs are chosen from context, so read is pronounced differently in "I read it" and "I have read it". You can also load a full CMUdict file for dictionary-grade coverage, or override one place inline with "say {K IH1 NG K OW1 B R AH0} now".
Styles, tags and SSML
Put a tag in square brackets anywhere in the text, and everything after it is spoken in that style:
tts.to_wav("Oh no [sigh] I really thought we had it. [sad] It's over. [laugh] Just kidding! [excited] We won!", "out.wav");
There are 54 built-in styles (35 moods and 19 manners), 17 sound events such as [laugh], [sigh] and [cough], and 24 interjections such as [wow] and [ugh]. Tags are forgiving about case and typos, so [wisper] resolves to whisper. Intensity words, numeric intensity and combinations work too: [very sad], [sad:0.5], [sad+whisper]. Each style is a bundle of 20 parameters, and you can define your own:
tts.define_style("grumpy", "angry", { pitch: -3, rate: 0.9, creak: 0.3, aliases: "cranky" });
tts.define_voice("hero", "male", { f0: 135, tract: 1.08, breath: 0.08 });
tts.to_wav("[grumpy] Get off my lawn.", "lawn.wav", { voice: "hero", pitch: -1 });
There are 10 built-in voices (male, female, child, teen, deep, elder, narrator, whisper, robot and alien), and you can define more. A subset of SSML is supported as well: break, prosody, emphasis, phoneme, sub, say-as, voice and mark.
Timing for subtitles and lip-sync
align returns the whole timeline: each word with start and end times, its phonemes, and each phoneme with a viseme, a mouth-shape id from 0 to 15.
let t = tts.align("Good morning, world.");
for (w in t.words) { print(w.word, w.start, w.end, w.phonemes); }
good 0.04 0.2558 G UH1 D
morning 0.2558 0.732889 M AO1 R N IH0 NG
world 0.902889 1.27509 W ER1 L D
The guide's worked example uses this to build an SRT subtitle file: it groups words into cues wherever a silence of 0.2 s or more appears. Here is what it produces for a short script:
1
00:00:00,040 --> 00:00:01,044
the kobold said
2
00:00:01,299 --> 00:00:02,574
king cobra is ready
3
00:00:02,954 --> 00:00:03,199
is it
4
00:00:03,598 --> 00:00:04,200
yes it is
Because synthesis is deterministic, the times from align line up with the audio from to_wav for the same text and options.
Speech is audio
speak returns a regular std.music_note buffer, so everything in that module applies to speech: filters, reverb, mixing and saving. The synthesizer runs at whatever sample rate you ask for, so render speech at sr=44100 or sr=48000 to match the music it will join, with no resampling step. A band-pass filter on the robot voice gives a radio effect in two lines:
let v = tts.speak("Robots do not dream.", "voice=robot");
let radio = music_note.filter(v, "bandpass", 1500.0);
Things the guide warns about
The "common mistakes" section is the most practical page:
-
A typo in an option name (
"rat=2") is silently ignored. Out-of-range values raise an error, but unknown names don't, so check withduration. -
rate=2doesn't halve the duration. The sentence goes from 2.858 s to 1.752 s, not 1.429 s, because consonants compress less than vowels. -
normalizedoesn't show tags or substitutions. Usewordsfor tags andphonemesfor the final result. -
Free buffers from
speakwithtts.free, or useto_wav, which frees its own. - Lexicon, substitutions, voices and styles are global to the running program, so define them once at start-up.
Speed and honest limits
The guide reports 30 copies of a sentence (88.9 s of speech) synthesized and written in 137 ms, about 650 times real time on its machine. Treat that as an order of magnitude, since your hardware will differ.
- It's a formant synthesizer. It's clear and fully controllable, but unmistakably synthetic. It isn't a neural voice.
-
English only. Other scripts are skipped, and foreign words go through English rules unless you add them with
add_word. - The dictionary is deliberately compact. The rule engine is about 85 to 90 percent accurate on regular vocabulary, so load a pronouncing dictionary for a specific domain.
- Styles and events are cues, not recordings. A laugh or a sigh is convincing as a signal, not as a human sound.
- Text up to 400,000 characters per call, and Roman numerals, chemical formulas and tables aren't interpreted.
Every example was run
The guide was written for KingCobra 1.0.0, and every program in it was run on the real interpreter, with the output shown as printed. The numbers that depend on the synthesizer (durations, frame counts, file sizes) are exact for the default settings and repeatable, because the synthesizer is deterministic. The work problems in Chapter 15 give five groups of problems with only the final answer, plus six open challenges. Chapter 14 is a 9-step verification checklist for speech code, and Appendix A is a cheat sheet.
Get started
- Guide (PDF): https://github.com/DivyanshuSinha136/KingCobra/blob/main/tutorial/KingCobra_std_tts_Complete_Guide.pdf
-
Repo: https://github.com/DivyanshuSinha136/KingCobra, with the compact reference in
docs/STD_TTS.mdand a runnable tour inexamples/std_tts.kc -
The pipeline in the source tree (
std/tts/):tts_text.c(normalisation, tags and SSML),tts_g2p.candtts_dict.c(pronunciation),tts_plan.c(prosody and durations),tts_style.c(styles) andtts_synth.c(the formant synthesizer) - New to the language? Start with the Complete Expert Guide or the tutorial folder. The guide assumes you know the language.
If a word comes out wrong, or you find a pronunciation or a style that behaves differently from the guide, please open an issue. A star on the repo helps other people find it.
Top comments (0)