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/

Commit 6f4b0e22f2

6f4b0e22f25aad65134dd124845590a5a803b7d5

parent: afbc417c28

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-09 20:54 UTC

Skip AAC priming on clip playback; warm up the clip player at launch

Each clip starts at the end of the encoder's 2112 priming frames (88 ms),
and a silent clip plays at launch so the first tap's clip is not delayed.
The sentence gap grows to keep the ~0.2 s pause between sentences.

Closes #10

Layout: unified · split

DayByDay/DayByDayApp.swift +1
@@ -41,6 +41,7 @@ struct DayByDayApp: App {
4141 let warmup = AVSpeechUtterance(string: "")
4242 warmup.volume = 0
4343 SpeechSynthesizer.shared.speakUtterance(warmup)
44 SpeechSynthesizer.shared.warmUpClips()
4445 }
4546 }
4647 }
DayByDay/Speech/ClipLibrary.swift +5
@@ -37,6 +37,11 @@ final class ClipLibrary {
3737 entries[sentence].map { Clip(url: directory.appendingPathComponent($0.file), seconds: $0.seconds) }
3838 }
3939
40 /// Any clip, for warming up playback.
41 var anyClip: Clip? {
42 entries.keys.min().flatMap(clip(for:))
43 }
44
4045 /// One clip per sentence of `text`, or nil if any sentence has none.
4146 func clips(for text: String) -> [Clip]? {
4247 let sentences = SpokenText.sentences(text)
DayByDay/SpeechSynthesizer.swift +18 −4
@@ -21,13 +21,18 @@ final class SpeechSynthesizer: NSObject, AVSpeechSynthesizerDelegate, AVAudioPla
2121
2222 /// Clips to play from; nil means always use the synthesizer.
2323 var library: ClipLibrary? = ClipLibrary.bundled
24 /// Gap between the sentences of a clip line. Each clip already starts with
25 /// ~90 ms of encoder lead-in and ends with ~40 ms of quiet, so the pause
26 /// a child hears is about 0.2 s.
27 static let sentenceGap = 0.05
24 /// Skipped at the start of every clip: the AAC encoder's 2112 priming
25 /// frames, which the ADTS files carry as silence.
26 static let leadIn = 2112.0 / 24_000
27 /// Gap between the sentences of a clip line. Each clip, after `leadIn`,
28 /// starts and ends with ~40 ms of quiet, so the pause a child hears is
29 /// about 0.2 s.
30 static let sentenceGap = 0.14
2831 /// Extra time past a clip's known length before a stalled clip is skipped.
2932 static let clipGrace = 1.5
3033 private var player: AVAudioPlayer?
34 /// Plays a clip silently at launch so the first real clip starts on time.
35 private var warmupPlayer: AVAudioPlayer?
3136 /// Counts players, so a watchdog only acts on the clip it was set for.
3237 private var playerID = 0
3338 private var queue: [ClipLibrary.Clip] = []
@@ -63,6 +68,14 @@ final class SpeechSynthesizer: NSObject, AVSpeechSynthesizerDelegate, AVAudioPla
6368 synthesizer.speak(utterance)
6469 }
6570
71 /// Loads the audio decoder and output by playing a clip at zero volume.
72 func warmUpClips() {
73 guard let url = library?.anyClip?.url, let player = try? AVAudioPlayer(contentsOf: url) else { return }
74 player.volume = 0
75 player.play()
76 warmupPlayer = player
77 }
78
6679 func speak(_ text: String, completion: (() -> Void)? = nil) {
6780 // A gentle tactile bump with every spoken line. Prepared just before
6881 // firing for lowest latency.
@@ -133,6 +146,7 @@ final class SpeechSynthesizer: NSObject, AVSpeechSynthesizerDelegate, AVAudioPla
133146 return
134147 }
135148 next.delegate = self
149 next.currentTime = Self.leadIn
136150 player = next
137151 playerID += 1
138152 let id = playerID
DayByDayTests/VoiceClipTests.swift +16
@@ -47,6 +47,22 @@ struct VoiceClipTests {
4747 #expect(off.isEmpty, "\(off.prefix(5))")
4848 }
4949
50 /// Playback skips `SpeechSynthesizer.leadIn`; none of it may hold speech.
51 @Test func leadInIsQuiet() throws {
52 let dir = try #require(Self.manifestURL).deletingLastPathComponent()
53 var loud: [String] = []
54 for e in Self.entries {
55 let file = try AVAudioFile(forReading: dir.appendingPathComponent(e.file))
56 let buffer = try #require(AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length)))
57 try file.read(into: buffer)
58 let samples = UnsafeBufferPointer(start: buffer.floatChannelData![0], count: Int(buffer.frameLength))
59 let peak = samples.map(abs).max() ?? 0
60 let skipped = Int(SpeechSynthesizer.leadIn * file.processingFormat.sampleRate)
61 if samples.prefix(skipped).contains(where: { abs($0) > 0.01 * peak }) { loud.append(e.text) }
62 }
63 #expect(loud.isEmpty, "\(loud.prefix(5))")
64 }
65
5066 @Test func onlyListedNamesHaveGreetings() {
5167 #expect(Set(Self.entries.map(\.text).filter { $0.hasPrefix("Hi, ") })
5268 == Set(Lines.spokenNames.map { "Hi, \($0)!" }))