Repository navigation
Expand file tree
/
Copy pathQueuePlayer.swift
More file actions
114 lines (97 loc) · 3.83 KB
/
Copy pathQueuePlayer.swift
File metadata and controls
114 lines (97 loc) · 3.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import AVFoundation
/// Plays a sequence of audio files back-to-back via AVQueuePlayer. Chunks
/// (paragraphs) are enqueued as they become ready (cache hit = immediately,
/// miss = after synthesis), so playback starts on the first chunk and the rest
/// stream in. pause()/resume() keep position; prev()/next() navigate by
/// paragraph (rebuilding the queue when jumping back). Small gaps between items
/// fall on paragraph boundaries (natural pauses).
final class QueuePlayer {
private let diagnosticID = MemoryDiagnostics.begin("queuePlayer.instance")
deinit { MemoryDiagnostics.end(diagnosticID) }
private let player = AVQueuePlayer()
var onFinish: (() -> Void)?
private var urls: [URL] = [] // every chunk URL, in order
private var playIndex = 0 // index of the currently-playing chunk
private var expected = 0
private var observers: [NSObjectProtocol] = []
init() { player.actionAtItemEnd = .advance }
var memorySummary: String {
"audioURLs=\(urls.count) audioItems=\(player.items().count) audioObservers=\(observers.count) audioExpected=\(expected)"
}
var isPlaying: Bool { player.rate != 0 }
var finishedCount: Int { playIndex }
var expectedCount: Int { expected }
var canNext: Bool { playIndex + 1 < urls.count } // a synthesized next chunk exists
var canPrev: Bool { playIndex > 0 }
var chunkFraction: Double { currentItemFraction } // 0…1 within the current paragraph
var chunkSeconds: Double { // playback position within the paragraph
guard let t = player.currentItem?.currentTime().seconds, t.isFinite else { return 0 }
return t
}
/// Begin a new sequence of `expected` chunks.
func start(expected: Int) {
stop()
self.expected = expected
}
func enqueue(_ url: URL) {
urls.append(url)
addItem(url)
if player.rate == 0 { player.play() }
}
private func addItem(_ url: URL) {
let item = AVPlayerItem(url: url)
let obs = NotificationCenter.default.addObserver(
forName: .AVPlayerItemDidPlayToEndTime, object: item, queue: .main
) { [weak self] _ in self?.itemFinished() }
observers.append(obs)
player.insert(item, after: nil)
}
private func itemFinished() {
playIndex += 1
if playIndex >= expected, expected > 0 { onFinish?() }
}
/// Skip to the next already-synthesized paragraph.
func next() {
guard canNext else { return }
playIndex += 1
player.advanceToNextItem()
player.play()
}
/// Jump back to the previous paragraph (rebuilds the queue from there).
func prev() {
guard canPrev else { return }
rebuild(from: playIndex - 1)
}
private func rebuild(from index: Int) {
clearObservers()
player.removeAllItems()
playIndex = index
for i in index..<urls.count { addItem(urls[i]) }
player.play()
}
func pause() { player.pause() }
func resume() { player.play() }
func stop() {
player.pause()
player.removeAllItems()
clearObservers()
urls.removeAll()
playIndex = 0
expected = 0
}
private func clearObservers() {
observers.forEach { NotificationCenter.default.removeObserver($0) }
observers.removeAll()
}
/// Overall progress across the whole sequence (0…1).
var progress: Double {
guard expected > 0 else { return 0 }
return min(1, (Double(playIndex) + currentItemFraction) / Double(expected))
}
private var currentItemFraction: Double {
guard let item = player.currentItem else { return 0 }
let dur = item.duration.seconds
guard dur.isFinite, dur > 0 else { return 0 }
return min(1, item.currentTime().seconds / dur)
}
}