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/

DayByDay/Quiz/CardVoice.swift

062549ad26607ce9e973ed2a9a7ef6f853885f83
daybyday/DayByDay/Quiz/CardVoice.swift history · blame · raw

53 lines · 1672 bytes

7 symbols in this file
 1//
 2//  CardVoice.swift
 3//  DayByDay
 4//
 5
 6import Foundation
 7
 8/// Tokens for spoken lines; only the latest one may still be said.
 9nonisolated struct LineQueue {
10    private var latest = 0
11
12    mutating func next() -> Int {
13        latest += 1
14        return latest
15    }
16
17    func isCurrent(_ token: Int) -> Bool { token == latest }
18
19    mutating func cancel() { latest += 1 }
20}
21
22/// Speaks a card's line, after its sound if it has one. A newer card, or
23/// leaving the screen, cancels a line that has not started yet.
24final class CardVoice {
25    static let shared = CardVoice()
26
27    private var queue = LineQueue()
28    /// The last card sound, which may still be playing under a new card's line.
29    private var lastSound: SoundEffect?
30
31    /// Wait for whichever sound is still playing, then a short gap.
32    nonisolated static func delay(newSound: Double, earlierSound: Double) -> Double {
33        let longest = max(newSound, earlierSound)
34        return longest > 0 ? longest + 0.2 : 0
35    }
36
37    func say(_ line: String, after sound: SoundEffect?) {
38        let token = queue.next()
39        SpeechSynthesizer.shared.stop()
40        if let sound { SoundEngine.shared.play(sound) }
41        let delay = Self.delay(newSound: sound.map(SoundEngine.shared.remaining) ?? 0,
42                               earlierSound: lastSound.map(SoundEngine.shared.remaining) ?? 0)
43        if sound != nil { lastSound = sound }
44        DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [self] in
45            if queue.isCurrent(token) { SpeechSynthesizer.shared.speak(line) }
46        }
47    }
48
49    func cancel() {
50        queue.cancel()
51        SpeechSynthesizer.shared.stop()
52    }
53}