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/SpeechSynthesizer.swift

062549ad26607ce9e973ed2a9a7ef6f853885f83
daybyday/DayByDay/SpeechSynthesizer.swift history · blame · raw

221 lines · 8807 bytes

15 symbols in this file
  1//
  2//  SpeechSynthesizer.swift
  3//  DayByDay
  4//
  5
  6import AVFoundation
  7import UIKit
  8
  9/// Speaks a line from pre-rendered voice clips, one per sentence, played back
 10/// to back. A line with any sentence missing from the clips is spoken whole by
 11/// AVSpeechSynthesizer with the best installed en-US voice, so a line never
 12/// mixes two voices.
 13final class SpeechSynthesizer: NSObject, AVSpeechSynthesizerDelegate, AVAudioPlayerDelegate {
 14    static let shared = SpeechSynthesizer()
 15
 16    private let synthesizer = AVSpeechSynthesizer()
 17    private let voice: AVSpeechSynthesisVoice?
 18    private let haptics = UIImpactFeedbackGenerator(style: .rigid)
 19    /// Run when the matching utterance finishes; dropped if it is cut off.
 20    private var completions: [ObjectIdentifier: () -> Void] = [:]
 21
 22    /// Clips to play from; nil means always use the synthesizer.
 23    var library: ClipLibrary? = ClipLibrary.bundled
 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
 31    /// Extra time past a clip's known length before a stalled clip is skipped.
 32    static let clipGrace = 1.5
 33    private var player: AVAudioPlayer?
 34    /// Plays a clip silently at launch so the first real clip starts on time.
 35    private var warmupPlayer: AVAudioPlayer?
 36    /// Counts players, so a watchdog only acts on the clip it was set for.
 37    private var playerID = 0
 38    private var queue: [ClipLibrary.Clip] = []
 39    private var clipCompletion: (() -> Void)?
 40    /// Bumped by every speak and stop, so a stale gap or finish does nothing.
 41    private var clipToken = 0
 42
 43    var isPlayingClips: Bool { player != nil }
 44
 45    private override init() {
 46        self.voice = Self.bestAvailableVoice()
 47        super.init()
 48        synthesizer.delegate = self
 49        NotificationCenter.default.addObserver(forName: AVAudioSession.interruptionNotification, object: nil,
 50                                               queue: .main) { [weak self] note in
 51            let raw = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt
 52            MainActor.assumeIsolated { self?.handleInterruption(raw.flatMap(AVAudioSession.InterruptionType.init)) }
 53        }
 54    }
 55
 56    /// A call, Siri or an alarm pauses the clip; it resumes when that ends.
 57    /// The watchdog in `playNextClip` ends the line if it never does.
 58    private func handleInterruption(_ type: AVAudioSession.InterruptionType?) {
 59        switch type {
 60        case .began: player?.pause()
 61        case .ended: player?.play()
 62        default: break
 63        }
 64    }
 65
 66    /// Speaks a pre-configured utterance directly. Used for warmup at launch.
 67    func speakUtterance(_ utterance: AVSpeechUtterance) {
 68        synthesizer.speak(utterance)
 69    }
 70
 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
 79    func speak(_ text: String, completion: (() -> Void)? = nil) {
 80        // A gentle tactile bump with every spoken line. Prepared just before
 81        // firing for lowest latency.
 82        haptics.prepare()
 83        haptics.impactOccurred()
 84
 85        // Ensure speech plays through the speaker even when the silent switch is on.
 86        try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
 87        try? AVAudioSession.sharedInstance().setActive(true)
 88
 89        stop()
 90
 91        #if DEBUG
 92        if let warning = missingClipWarning(for: text) { assertionFailure(warning) }
 93        #endif
 94        if let clips = library?.clips(for: text) {
 95            queue = clips
 96            clipCompletion = completion
 97            playNextClip(token: clipToken)
 98            return
 99        }
100
101        let utterance = AVSpeechUtterance(string: text)
102        utterance.voice = voice
103        utterance.rate = 0.4
104        utterance.pitchMultiplier = 1.0
105        utterance.preUtteranceDelay = 0
106        if let completion { completions[ObjectIdentifier(utterance)] = completion }
107        synthesizer.speak(utterance)
108    }
109
110    /// Names the sentences the bundled clips lack. Every spoken line belongs
111    /// in `SpokenLines`; one that is missing plays in the system voice.
112    func missingClipWarning(for text: String) -> String? {
113        guard let library, library === ClipLibrary.bundled else { return nil }
114        let missing = SpokenText.sentences(text).filter { library.clip(for: $0) == nil }
115        guard !missing.isEmpty else { return nil }
116        return "No voice clip for \(missing). Add the line to SpokenLines and render it."
117    }
118
119    /// Stops clips and speech; neither calls its completion.
120    func stop() {
121        clipToken += 1
122        player?.delegate = nil
123        player?.stop()
124        player = nil
125        queue = []
126        clipCompletion = nil
127        if synthesizer.isSpeaking {
128            synthesizer.stopSpeaking(at: .immediate)
129        }
130    }
131
132    private func playNextClip(token: Int) {
133        guard token == clipToken else { return }
134        guard !queue.isEmpty else {
135            player = nil
136            let completion = clipCompletion
137            clipCompletion = nil
138            completion?()
139            return
140        }
141        let clip = queue.removeFirst()
142        guard let next = try? AVAudioPlayer(contentsOf: clip.url) else {
143            // An unreadable clip ends the line rather than stalling it.
144            queue = []
145            playNextClip(token: token)
146            return
147        }
148        next.delegate = self
149        next.currentTime = Self.leadIn
150        player = next
151        playerID += 1
152        let id = playerID
153        if !next.play() {
154            advance(from: id, token: token)
155            return
156        }
157        // If the clip never reports finishing (interrupted, backgrounded,
158        // a decode error), move on once its length plus a grace period passes.
159        DispatchQueue.main.asyncAfter(deadline: .now() + clip.seconds + Self.clipGrace) { [self] in
160            advance(from: id, token: token)
161        }
162    }
163
164    /// Ends clip `id` and goes to the next sentence, if that clip is still current.
165    private func advance(from id: Int, token: Int) {
166        guard token == clipToken, id == playerID, let current = player else { return }
167        current.delegate = nil
168        current.stop()
169        if queue.isEmpty {
170            playNextClip(token: token)
171        } else {
172            DispatchQueue.main.asyncAfter(deadline: .now() + Self.sentenceGap) { [self] in
173                playNextClip(token: token)
174            }
175        }
176    }
177
178    nonisolated func audioPlayerDidFinishPlaying(_ finished: AVAudioPlayer, successfully flag: Bool) {
179        playerEnded(finished)
180    }
181
182    nonisolated func audioPlayerDecodeErrorDidOccur(_ failed: AVAudioPlayer, error: Error?) {
183        playerEnded(failed)
184    }
185
186    /// Holding the player keeps its identity unique until the check runs.
187    private nonisolated func playerEnded(_ ended: AVAudioPlayer) {
188        nonisolated(unsafe) let ended = ended
189        Task { @MainActor in
190            guard let player, player === ended else { return }
191            advance(from: playerID, token: clipToken)
192        }
193    }
194
195    nonisolated func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
196        let id = ObjectIdentifier(utterance)
197        Task { @MainActor in completions.removeValue(forKey: id)?() }
198    }
199
200    nonisolated func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
201        let id = ObjectIdentifier(utterance)
202        Task { @MainActor in _ = completions.removeValue(forKey: id) }
203    }
204
205    /// Picks the best en-US voice on the device.
206    /// Filters for en-US, excludes novelty voices, then sorts by quality
207    /// descending so premium (3) > enhanced (2) > default (1).
208    private static func bestAvailableVoice() -> AVSpeechSynthesisVoice? {
209        let best = AVSpeechSynthesisVoice.speechVoices()
210            .filter { voice in
211                voice.language.hasPrefix("en-US")
212                && !voice.voiceTraits.contains(.isNoveltyVoice)
213            }
214            .sorted { $0.quality.rawValue > $1.quality.rawValue }
215            .first
216
217        let selected = best ?? AVSpeechSynthesisVoice(language: "en-US")
218        print("[DayByDay] Selected voice: \(selected?.name ?? "nil"), quality: \(selected?.quality.rawValue ?? -1)")
219        return selected
220    }
221}