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/Speech/ClipLibrary.swift

main
daybyday/DayByDay/Speech/ClipLibrary.swift history · blame · raw

56 lines · 1811 bytes

5 symbols in this file
 1//
 2//  ClipLibrary.swift
 3//  DayByDay
 4//
 5
 6import Foundation
 7
 8/// Pre-rendered voice clips, one per sentence, listed in `voice-manifest.json`.
 9final class ClipLibrary {
10    struct Entry: Decodable {
11        let text: String
12        let file: String
13        let seconds: Double
14    }
15
16    private let entries: [String: Entry]
17    private let directory: URL
18
19    init?(manifest: URL, directory: URL) {
20        guard let data = try? Data(contentsOf: manifest),
21              let list = try? JSONDecoder().decode([Entry].self, from: data) else { return nil }
22        entries = Dictionary(list.map { ($0.text, $0) }, uniquingKeysWith: { a, _ in a })
23        self.directory = directory
24    }
25
26    /// The clips that ship in the app bundle, if any.
27    static let bundled: ClipLibrary? = Bundle.main.url(forResource: "voice-manifest", withExtension: "json")
28        .flatMap { ClipLibrary(manifest: $0, directory: $0.deletingLastPathComponent()) }
29
30    struct Clip {
31        let url: URL
32        /// Playback length, used to skip a clip that never reports finishing.
33        let seconds: Double
34    }
35
36    func clip(for sentence: String) -> Clip? {
37        entries[sentence].map { Clip(url: directory.appendingPathComponent($0.file), seconds: $0.seconds) }
38    }
39
40    /// Any clip, for warming up playback.
41    var anyClip: Clip? {
42        entries.keys.min().flatMap(clip(for:))
43    }
44
45    /// One clip per sentence of `text`, or nil if any sentence has none.
46    func clips(for text: String) -> [Clip]? {
47        let sentences = SpokenText.sentences(text)
48        guard !sentences.isEmpty else { return nil }
49        var result: [Clip] = []
50        for sentence in sentences {
51            guard let clip = clip(for: sentence) else { return nil }
52            result.append(clip)
53        }
54        return result
55    }
56}