krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

docs/superpowers/specs/2026-10-16-better-voice.md

main
daybyday/docs/superpowers/specs/2026-10-16-better-voice.md rendered · source · history · blame · raw

338 lines · 18310 bytes

18 symbols in this file
  1# Better spoken voice
  2
  3## Intent
  4
  5Every prompt in DayByDay is spoken, and on most devices it is spoken by the
  6compact default en-US voice, which sounds robotic. `SpeechSynthesizer` already
  7picks the best installed en-US voice (premium > enhanced > default) at rate
  80.4, but enhanced and premium voices are only present if someone downloaded
  9them in Settings. This spec compares ways to make the voice sound better and
 10picks one. It is a plan; no app code changes with it.
 11
 12## Constraints
 13
 14- No network use, accounts, analytics or ads. Nothing is downloaded by the app.
 15- All art and sound is made in code or generated. No camera, microphone or
 16  parent-recorded voice (this rules out Personal Voice).
 17- Every prompt is spoken. en-US only.
 18- App target deployment is iOS 17.5.
 19- Games advance from the `speak(_:completion:)` completion. A completion must
 20  fire once when the line ends, and must not fire for a line that is cut off
 21  (`SpeechCompletionTests`).
 22- The learning-games spec (2026-10-16-learning-games-design.md) says "No
 23  bundled image or audio files beyond the existing app icon." The user
 24  approved an exception for generated speech clips (Decisions, 1); amend that
 25  line in the same change that adds the clips.
 26
 27## What is spoken
 28
 29Spoken text comes from about 20 call sites (`SpeechSynthesizer.shared.speak`
 30and `CardVoice.say`). Apart from profile names, every line is a fixed string or
 31a template filled from a closed set: item names, `DayOfWeek`, `MonthOfYear`,
 32seasons, `DayPicture` kinds, weather, clothing, numbers, praise phrases
 33(`PraisePhrases.all`), corrections, and the routine lines in `RoutineScript`.
 34So the full set of lines, minus names, can be enumerated.
 35
 36The largest template is the sticker calendar's
 37`"On \(monthName) \(day), it was \(weather)."` (12 × up to 31 × weather
 38kinds, roughly 2,000 lines). Everything else together is in the low thousands
 39at most. Lines that contain a profile name: `"Hi, \(name)!"` in
 40`ProfilePickerView` and `RoutineScript`. Per Decisions, 4, these are spoken as
 41`"Hi there!"` (the name stays on screen), so no spoken line contains a name.
 42
 43## Options
 44
 45### A. Get enhanced or premium Apple voices onto the device
 46
 47The app cannot download a voice or start a download. No such API exists;
 48`AVSpeechSynthesisVoice(identifier:)` returns nil for a voice that is "not yet
 49downloaded by the user", and enhanced and premium voices are documented as
 50ones "you must download to use".
 51
 52What the parent does: Settings > Accessibility > Spoken Content > Voices >
 53English (iOS 17 and 18), or Settings > Accessibility > Read & Speak > Voices
 54(iOS 26), then download an enhanced or premium US voice. Apple says
 55enhanced-quality voices "can be 100 MB or larger" and to use Wi-Fi. That
 56download is done by iOS, not by the app, so it does not break the no-network
 57rule, but it does depend on a parent finding and following the steps.
 58
 59App work: show a parent-area notice when the selected voice is `.default`,
 60with the Settings path spelled out (children can't read it, so it lives behind
 61the parent gate). Re-run voice selection when the app returns to the
 62foreground; `voice` is currently a `let` chosen once at init.
 63`AVSpeechSynthesizer.availableVoicesDidChangeNotification` (iOS 17+) exists,
 64but its docs do not say it fires for downloaded Apple voices, so rely on the
 65foreground check.
 66
 67- App size: none.
 68- Effort: 0.5–1 day.
 69- Timing risk: none. Same synthesizer and delegate.
 70- Result: much better voice on devices where a parent acts; no change
 71  anywhere else, which is most devices today.
 72
 73### B. Bundled audio for every enumerable line, system voice for names
 74
 75Render every line except those containing names ahead of time with an
 76open-license neural TTS model on a Mac, ship the clips in the app, and play
 77them with `AVAudioPlayer`. Lines with a name, and any line without a clip, go
 78to `AVSpeechSynthesizer` as now.
 79
 80Which model renders the clips:
 81
 82- System voices are out. The macOS Tahoe license allows System Voices only "for
 83  your personal, non-commercial use" and bars their "recording, publishing or
 84  redistribution … in a profit, non-profit, public sharing or commercial
 85  context". `AVSpeechSynthesizer.write(_:toBufferCallback:)` can render audio,
 86  but shipping that audio is not allowed.
 87- Kokoro-82M: Apache-2.0 weights; misaki G2P is Apache-2.0 and runs without
 88  espeak-ng when `fallback=None` (unknown words then need hand-written
 89  phonemes). en-US voices `af_heart` (grade A) and `af_bella` (A-) are the
 90  best rated. Output is 24 kHz.
 91- Piper voices are a poor fit: en_US-lessac comes from a research-only dataset
 92  and hfc_female is CC BY-NC-SA. ljspeech (public domain) is usable but lower
 93  quality than Kokoro.
 94- GPL tools used only on the build Mac do not make their output GPL, and none
 95  ship in the app.
 96
 97Known model limits:
 98
 99- Kokoro's voice notes say voices are weak on short utterances, "especially
100  less than 10-20 tokens". Single words ("Monday", "Super!") are most of the
101  card lines. Mitigation: render each short line inside a carrier sentence and
102  trim it, or re-render with other seeds until a listener accepts it. Every
103  clip gets a listening review regardless.
104- Output is not bit-identical between runs (the vocoder samples noise). Seed
105  the generator; clips are rendered once and committed, so this only matters
106  when re-rendering.
107
108Size: speech compressed as mono AAC at ~32 kbps is ~4 KB per second. At
109roughly 3,000 lines averaging 1.5 s, the clips come to ~18 MB. Rewording the
110sticker calendar line to drop the date ("It was sunny.", with the date shown
111on screen) would remove ~2,000 of those lines and bring the total to a few MB.
112
113Mixed voices: "Hi, Maya!" would be the system voice while the rest of the app
114is Kokoro. Stitching a Kokoro "Hi," to a system-voice name sounds worse than
115either alone. Decided (Decisions, 4): the two greeting call sites speak
116`"Hi there!"` instead, so every line comes from the clips and the synthesizer
117is only a fallback for a missing clip.
118
119Completion timing: `AVAudioPlayerDelegate.audioPlayerDidFinishPlaying` gives
120the same "ended" signal, and `stop()` on a player sends no finish callback, so
121the current rule (no completion for a line that was cut off) carries over.
122Clip lengths are known up front, which makes timing more predictable than TTS.
123The risk is in the switch between paths: `stop()` and `isSpeaking` must cover
124both the player and the synthesizer, or a clip and an utterance could overlap.
125
126- App size: ~18 MB with every calendar combination (decided), or a few MB with
127  the calendar line reworded.
128- Effort: 5–7 days (render pipeline 1.5, line catalog 1.5, player and fallback
129  1, tests 1, listening review and re-renders 1–2).
130- Timing risk: low, if both paths sit behind the existing `speak` and `stop`.
131- Result: the same good voice on every device, for every line (names are no
132  longer spoken; Decisions, 4).
133
134### C. Neural TTS model running on device
135
136- Every Kokoro Swift/Core ML/MLX port found (kokoro-ios, kokoro-coreml,
137  FluidAudio, speech-swift) requires iOS 18. Using one means raising the
138  deployment target from 17.5.
139- The only iOS 13+ runtime that runs Kokoro, Piper, Matcha or Kitten is
140  sherpa-onnx, and its iOS build statically links espeak-ng (GPL-3.0-or-later),
141  which conflicts with App Store distribution. A custom ONNX Runtime + Kokoro +
142  misaki-style G2P path without espeak would avoid that, but no package exists.
143- Size: Kokoro is 86–163 MB as quantized/fp16 ONNX and ~178 MB as the Core ML
144  set. FluidAudio's 8M-parameter distillation is 12 MB int8, one voice, and its
145  README says physical iOS inference is unvalidated.
146- Latency: kokoro-coreml measured 1,383 ms to produce 3 s of audio on an
147  iPhone 12 Pro (A14), 702 ms on an iPhone 15 Pro Max. The first load spends
148  several seconds compiling the model. kokoro-ios (MLX) ran out of memory on
149  an iPhone 12 Pro for 30 s clips. No data for A12/A13 iPads.
150- The short-utterance weakness in B applies here too, and it can't be fixed by
151  a human listening to each clip.
152
153- App size: 12–180 MB.
154- Effort: 8–12 days, plus a deployment-target change or a custom G2P.
155- Timing risk: high. Every line waits ~0.5–1.5 s before sound starts on older
156  devices, and memory pressure on 4 GB devices can kill synthesis mid-line.
157- Result: names would match the rest of the voice. Nothing else is better than
158  B.
159
160### D. Tune AVSpeechSynthesizer
161
162- `rate` runs 0.0–1.0 with default 0.5; the app uses 0.4. `pitchMultiplier`
163  runs 0.5–2.0. A slightly higher pitch (about 1.1) and per-line pauses may
164  sound friendlier to young children; it needs a listening test.
165- SSML (`AVSpeechUtterance(ssmlRepresentation:)`, iOS 16+) ignores `rate` and
166  `pitchMultiplier`; prosody has to come from `<prosody>` instead. Apple lists
167  no supported elements beyond the `<break>` and `<prosody>` shown at WWDC23.
168  Forum reports describe audible pauses around `<sub>`/`<phoneme>` and a freeze
169  with `<emphasis>`. Not worth the risk for small gains.
170- `preUtteranceDelay` and `postUtteranceDelay` add gaps; `didFinish` ignores
171  the final utterance's `postUtteranceDelay`.
172- None of this changes the compact voice's timbre, which is the main problem.
173
174- App size: none.
175- Effort: 0.5 day.
176- Timing risk: low for rate/pitch; medium for SSML.
177- Result: small.
178
179## Comparison
180
181| Option | App size | Effort | Timing risk | Who benefits |
182|---|---|---|---|---|
183| A. Settings voices + parent notice | 0 | 0.5–1 d | none | devices where a parent downloads a voice |
184| B. Bundled Kokoro clips, names not spoken (decided) | ~18 MB | 5–7 d | low | every device |
185| C. On-device neural TTS | 12–180 MB | 8–12 d | high | every device, iOS 18+ only |
186| D. Rate/pitch/SSML tuning | 0 | 0.5 d | low–medium | marginal |
187
188## Recommendation
189
190B, with A included. B gives every child the same good voice without a parent
191doing anything, keeps the iOS 17.5 target, ships nothing GPL, and has the most
192predictable completion timing. A costs half a day and improves the lines B
193cannot cover (names and any missing clip). C is rejected on size, iOS 18,
194latency on older iPads, and the espeak-ng license. D's rate/pitch change can
195be tried during B's listening review but is not a separate part.
196
197## Decisions
198
199Made by the user on 2026-10-17:
200
2011. Bundled audio: allowed for generated speech clips only. The learning-games
202   spec line "No bundled image or audio files" is amended when B is built.
2032. Voice: ElevenLabs Jessica on `eleven_v4`, with tone tags (`[excited]`
204   for praise, `[gently]` for corrections, `[curious]` for questions), chosen
205   over Kokoro `af_heart` and the Matilda, Sarah and v3 renders in a listening
206   test of 18 app lines. Letters are sent as capitals, except g, h, i, u, w, y
207   and z, which are sent as names ("Gee", "Aitch", "Eye", "You", "Double-you",
208   "Why", "Zee"). Rendered with `scripts/render-voice-elevenlabs.py` on a plan
209   that includes a commercial license. Kokoro `af_heart`
210   (`scripts/render-voice.py`, see Listening test) stays as the open-licensed
211   fallback renderer.
2123. Sticker calendar: keep the date and render every combination
213   (`"On \(month) \(day), it was \(weather)."`, about 2,000 clips), accepting
214   ~18 MB in total.
2154. Names: dropped from speech. The greeting is spoken as `"Hi there!"` in the
216   clip voice; the child's name stays on screen. No line falls back to the
217   system voice by design. Amended: names in `Lines.spokenNames` (Gianna, Gigi,
218   Ashlynn, Ash, Olive, Ollie, Elijah, Arthur, Noah, Thad, Thadeus, Izzy,
219   Isabella, Sam, Sammy, Frankie, Franklin) have recorded greetings
220   (`"Hi, Gianna!"`), matched ignoring case and surrounding spaces; any other
221   name gets `"Hi there!"`.
222
223## Listening test
224
225Rendered on a Mac with Kokoro 0.9.4 (Python 3.12 via `uv`, torch 2.14.1),
22624 kHz, seed 0, misaki dictionary only (espeak fallback disabled). Lines:
227"Monday", "Super!", "Can you find the cow?", "Hi there!", "That's Thursday!
228Try again.", "On October 3, it was sunny.", "Today is swim day!", "You did
229it!". No clipping; peaks 0.26–0.45, RMS within about 1 dB between voices.
230Setup notes for `scripts/render-voice.py`:
231
232- The `espeakng-loader` wheel's library points at its build machine's data
233  folder and exits the process when espeak is used. Since the plan runs
234  without espeak, replace `misaki.espeak.EspeakFallback` with a class whose
235  constructor raises, so `KPipeline` falls back to `None`.
236- misaki installs the spaCy `en_core_web_sm` model on first use through pip,
237  which a `uv` venv lacks. Install it up front:
238  `en_core_web_sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.8.0/en_core_web_sm-3.8.0-py3-none-any.whl`.
239
240## Build outline
241
242### Files
243
244- `DayByDay/Speech/SpokenLines.swift` (new): enumerates every line the app can
245  speak by calling the same functions the games use
246  (`QuestionPicker` prompts, `PraisePhrases.all`, `PraisePhrases.correction`,
247  `RoutineScript`, `SequencePuzzle`, `SortRound`, `MixColors`, `OrderSources`,
248  `StickerCalendarView` line, card names). Producers that build strings inline
249  move that string into a static function so the catalog and the view share it.
250- `DayByDay/Speech/ClipLibrary.swift` (new): loads `Voice/manifest.json`
251  (text → file name, duration) and looks up a clip by exact text.
252- `DayByDay/SpeechSynthesizer.swift`: `speak` plays a clip through
253  `AVAudioPlayer` when the library has one, otherwise uses the synthesizer.
254  `stop`, the haptic, the `.playback` session and the completion rule cover
255  both paths. `voice` becomes re-selectable on foreground (option A).
256- `DayByDay/DayByDayApp.swift`: warmup also preloads the manifest.
257- `DayByDay/Parent/ParentAreaView.swift`: notice with the Settings path when
258  the selected voice is `.default`.
259- `DayByDay/Voice/` (new, resources): `manifest.json` and `.m4a` clips (mono
260  AAC, 24 kHz). File names are a hash of the line text.
261- `scripts/render-voice-elevenlabs.py` (new): the same as `render-voice.py`
262  below with ElevenLabs as the engine (Decisions, 2). Reads the API key from
263  `ELEVENLABS_API_KEY`; `--dry-run` prints the text sent for each line.
264- `scripts/render-voice.py` (new): reads the exported line list, renders
265  missing lines with Kokoro (pinned version, fixed seed, misaki with no espeak
266  fallback, carrier sentences for short lines), trims, converts with
267  `afconvert`, and rewrites the manifest. Runs on a Mac, never in the app.
268- `DayByDayTests/ReviewExport.swift`: add `lines()`, which writes
269  `SpokenLines.all` to `EXPORT_DIR/lines.txt` for the render script, following
270  the existing sounds/tiles export.
271
272### Tests
273
274- Every line in `SpokenLines.all` has a clip in the manifest, and every
275  manifest entry is in `SpokenLines.all` (no stale clips).
276- Sample real producers (seeded rounds of each game, `RoutineScript` for every
277  day of a year, every `PraisePhrases` value) and check each produced line is
278  in `SpokenLines.all`. This catches a new template that the catalog missed.
279- `SpeechCompletionTests`: run both existing tests against a clip line and a
280  fallback line; add one where a clip is cut off by a TTS line and the reverse,
281  checking only the second completion fires.
282- No line in `SpokenLines.all` contains a profile name; the picker and
283  routine greetings speak `"Hi there!"`.
284- A line with no clip falls back to the synthesizer.
285- Manifest durations match the files (within 50 ms).
286- Voice re-selection picks a higher-quality voice when one is added (inject the
287  voice list).
288
289### Review
290
291The clips go through the art/sound reviewer like any other sound. Short lines
292get a listen each; a rejected clip is re-rendered with another seed or a
293different carrier sentence.
294
295## Sources
296
297Apple:
298
299- https://developer.apple.com/documentation/avfaudio/avspeechsynthesisvoicequality
300- https://developer.apple.com/documentation/avfaudio/avspeechsynthesisvoicequality/enhanced
301- https://developer.apple.com/documentation/avfaudio/avspeechsynthesisvoicequality/premium
302- https://developer.apple.com/documentation/avfaudio/avspeechsynthesisvoice/speechvoices()
303- https://support.apple.com/guide/iphone/iph96b214f0/18.0/ios/18.0
304- https://support.apple.com/guide/iphone/iph96b214f0/26.0/ios/26.0
305- https://support.apple.com/en-us/111798
306- https://developer.apple.com/documentation/avfaudio/avspeechsynthesizer/availablevoicesdidchangenotification
307- https://developer.apple.com/documentation/avfaudio/avspeechutterance/init(ssmlrepresentation:)-8zam9
308- https://developer.apple.com/videos/play/wwdc2023/10033/
309- https://developer.apple.com/forums/thread/712411
310- https://developer.apple.com/documentation/avfaudio/avspeechutterance/rate
311- https://developer.apple.com/documentation/avfaudio/avspeechutterance/pitchmultiplier
312- https://developer.apple.com/documentation/avfaudio/avspeechutterance/postutterancedelay
313- https://developer.apple.com/documentation/avfaudio/avspeechsynthesizer/write(_:tobuffercallback:)
314- https://developer.apple.com/documentation/avfaudio/avspeechsynthesizerdelegate/speechsynthesizer(_:didfinish:)
315- https://developer.apple.com/documentation/avfaudio/avspeechsynthesizerdelegate/speechsynthesizer(_:didcancel:)
316- https://www.apple.com/legal/sla/docs/macOSTahoe.pdf (section F, Voices)
317- https://www.apple.com/legal/sla/docs/iOS26_iPadOS26.pdf
318- https://developer.apple.com/forums/thread/812285
319
320Neural TTS:
321
322- https://huggingface.co/hexgrad/Kokoro-82M
323- https://huggingface.co/hexgrad/Kokoro-82M/blob/main/VOICES.md
324- https://github.com/hexgrad/kokoro
325- https://raw.githubusercontent.com/hexgrad/kokoro/main/kokoro/istftnet.py
326- https://github.com/hexgrad/misaki
327- https://huggingface.co/onnx-community/Kokoro-82M-v1.0-ONNX
328- https://github.com/mlalma/kokoro-ios
329- https://huggingface.co/mattmireles/kokoro-coreml
330- https://github.com/FluidInference/FluidAudio
331- https://soniqo.audio/guides/kokoro
332- https://github.com/k2-fsa/sherpa-onnx
333- https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/master/build-ios.sh
334- https://github.com/espeak-ng/espeak-ng
335- https://github.com/OHF-Voice/piper1-gpl/blob/main/docs/VOICES.md
336- https://www.cstr.ed.ac.uk/projects/blizzard/2013/lessac_blizzard2013/license.html
337- https://huggingface.co/rhasspy/piper-voices/blob/main/en/en_US/hfc_female/medium/MODEL_CARD
338- https://www.gnu.org/licenses/gpl-faq.html#WhatCaseIsOutputGPL