Skip to content

Commit 3a13fd8

Browse files
Lee Seongjooclaude
andcommitted
HUD: show TTS/해설 mode + standard paragraph transport
The floating HUD showed the full script text and only a stop control. Make it a proper transport: - Show a mode badge (🔊 TTS vs 📖 해설) + paragraph counter instead of the script text. AppState tags each playback path with playbackMode (대본/원본/replay → tts, 해설/이어서/services-explain → explain). - Standard controls: ⏮ previous paragraph · ⏯ play/pause · ⏭ next paragraph · ⏹ stop, with the progress bar. Prev/next disabled at the ends. - QueuePlayer gains paragraph navigation: next() advances to the next synthesized chunk; prev() rebuilds the queue from the previous chunk. It retains the chunk URLs and tracks playIndex (replacing the finished counter). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 53481f7 commit 3a13fd8

3 files changed

Lines changed: 105 additions & 39 deletions

File tree

‎Sources/App/AppState.swift‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,14 @@ final class AppState: ObservableObject {
147147
enum Phase: Equatable { case idle, synthesizing, playing, paused }
148148
@Published var phase: Phase = .idle
149149
@Published var progress: Double = 0 // 0…1 across all chunks
150+
151+
/// What the current playback is — shown in the HUD instead of the script text.
152+
enum PlaybackMode { case tts, explain
153+
var label: String { self == .tts ? "TTS" : "해설" }
154+
var icon: String { self == .tts ? "speaker.wave.2.fill" : "text.book.closed.fill" }
155+
}
156+
@Published var playbackMode: PlaybackMode = .tts
157+
150158
@Published var currentText = "" // text being spoken (overlay label)
151159
@Published var inputText = "" // original (top panel / source text)
152160
@Published var scriptText = "" // TTS-friendly script actually sent to the engine (bottom panel)
@@ -657,6 +665,7 @@ final class AppState: ObservableObject {
657665
func speakContinue() {
658666
let seg = lastSegment.trimmingCharacters(in: .whitespacesAndNewlines)
659667
guard !seg.isEmpty else { return }
668+
playbackMode = .explain
660669
synthesize(TextSplitter.cleanInput(seg)) // read the latest 해설 segment directly
661670
}
662671

@@ -675,6 +684,7 @@ final class AppState: ObservableObject {
675684
func speakExplanation() {
676685
let text = TextSplitter.cleanInput(explanationText)
677686
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
687+
playbackMode = .explain
678688
synthesize(text)
679689
}
680690

@@ -684,6 +694,7 @@ final class AppState: ObservableObject {
684694
/// through to speaking the source. Runs under `explainTask` so 중지 cancels it.
685695
func explainAndSpeak(_ code: String) {
686696
task?.cancel(); player.stop()
697+
playbackMode = .explain
687698
codeText = code // raw — no cleanInput
688699
explanationText = ""
689700
phase = .synthesizing
@@ -829,6 +840,7 @@ final class AppState: ObservableObject {
829840

830841
/// Generate-tab "재생": speak the script (or the original if it is empty).
831842
func speakScript() {
843+
playbackMode = .tts
832844
if scriptText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
833845
inputText = TextSplitter.cleanInput(inputText)
834846
synthesize(inputText)
@@ -840,6 +852,7 @@ final class AppState: ObservableObject {
840852
/// Services entry: set the source, build the script, then speak it.
841853
func speakSelected(_ text: String) {
842854
task?.cancel(); player.stop()
855+
playbackMode = .tts
843856
inputText = TextSplitter.cleanInput(text)
844857
scriptText = ""
845858
phase = .synthesizing
@@ -853,6 +866,7 @@ final class AppState: ObservableObject {
853866

854867
func replay(_ e: HistoryEntry) {
855868
task?.cancel(); player.stop()
869+
playbackMode = .tts
856870
guard let url = cache.fileURL(forKey: e.id) else { statusText = "오디오 파일 없음"; return }
857871
cache.touch(e.id); historyRevision += 1
858872
inputText = e.text; currentText = e.text
@@ -864,6 +878,16 @@ final class AppState: ObservableObject {
864878

865879
func stop() { explainTask?.cancel(); scriptTask?.cancel(); task?.cancel(); player.stop(); finish() }
866880

881+
// HUD transport: paragraph navigation.
882+
var canSkipNext: Bool { isBusy && player.canNext }
883+
var canSkipPrev: Bool { isBusy && player.canPrev }
884+
func skipNext() { guard player.canNext else { return }; player.next(); resumeIfPaused() }
885+
func skipPrev() { guard player.canPrev else { return }; player.prev(); resumeIfPaused() }
886+
private func resumeIfPaused() {
887+
if phase == .paused { phase = .playing; startTimer() }
888+
tick()
889+
}
890+
867891
func deleteHistory(_ id: String) { cache.delete(id); historyRevision += 1 }
868892
func clearHistory() { cache.clear(); historyRevision += 1 }
869893

‎Sources/Core/QueuePlayer.swift‎

Lines changed: 46 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,42 +3,72 @@ import AVFoundation
33
/// Plays a sequence of audio files back-to-back via AVQueuePlayer. Chunks
44
/// (paragraphs) are enqueued as they become ready (cache hit = immediately,
55
/// miss = after synthesis), so playback starts on the first chunk and the rest
6-
/// stream in. pause()/resume() keep position; small gaps between items fall on
7-
/// paragraph boundaries (natural pauses).
6+
/// stream in. pause()/resume() keep position; prev()/next() navigate by
7+
/// paragraph (rebuilding the queue when jumping back). Small gaps between items
8+
/// fall on paragraph boundaries (natural pauses).
89
final class QueuePlayer {
910
private let player = AVQueuePlayer()
1011
var onFinish: (() -> Void)?
1112

13+
private var urls: [URL] = [] // every chunk URL, in order
14+
private var playIndex = 0 // index of the currently-playing chunk
1215
private var expected = 0
13-
private var finished = 0
1416
private var observers: [NSObjectProtocol] = []
1517

1618
init() { player.actionAtItemEnd = .advance }
1719

1820
var isPlaying: Bool { player.rate != 0 }
19-
var finishedCount: Int { finished }
21+
var finishedCount: Int { playIndex }
2022
var expectedCount: Int { expected }
23+
var canNext: Bool { playIndex + 1 < urls.count } // a synthesized next chunk exists
24+
var canPrev: Bool { playIndex > 0 }
2125

2226
/// Begin a new sequence of `expected` chunks.
2327
func start(expected: Int) {
2428
stop()
2529
self.expected = expected
26-
self.finished = 0
2730
}
2831

2932
func enqueue(_ url: URL) {
33+
urls.append(url)
34+
addItem(url)
35+
if player.rate == 0 { player.play() }
36+
}
37+
38+
private func addItem(_ url: URL) {
3039
let item = AVPlayerItem(url: url)
3140
let obs = NotificationCenter.default.addObserver(
3241
forName: .AVPlayerItemDidPlayToEndTime, object: item, queue: .main
3342
) { [weak self] _ in self?.itemFinished() }
3443
observers.append(obs)
3544
player.insert(item, after: nil)
36-
if player.rate == 0 { player.play() }
3745
}
3846

3947
private func itemFinished() {
40-
finished += 1
41-
if finished >= expected, expected > 0 { onFinish?() }
48+
playIndex += 1
49+
if playIndex >= expected, expected > 0 { onFinish?() }
50+
}
51+
52+
/// Skip to the next already-synthesized paragraph.
53+
func next() {
54+
guard canNext else { return }
55+
playIndex += 1
56+
player.advanceToNextItem()
57+
player.play()
58+
}
59+
60+
/// Jump back to the previous paragraph (rebuilds the queue from there).
61+
func prev() {
62+
guard canPrev else { return }
63+
rebuild(from: playIndex - 1)
64+
}
65+
66+
private func rebuild(from index: Int) {
67+
clearObservers()
68+
player.removeAllItems()
69+
playIndex = index
70+
for i in index..<urls.count { addItem(urls[i]) }
71+
player.play()
4272
}
4373

4474
func pause() { player.pause() }
@@ -47,16 +77,21 @@ final class QueuePlayer {
4777
func stop() {
4878
player.pause()
4979
player.removeAllItems()
80+
clearObservers()
81+
urls.removeAll()
82+
playIndex = 0
83+
expected = 0
84+
}
85+
86+
private func clearObservers() {
5087
observers.forEach { NotificationCenter.default.removeObserver($0) }
5188
observers.removeAll()
52-
expected = 0
53-
finished = 0
5489
}
5590

5691
/// Overall progress across the whole sequence (0…1).
5792
var progress: Double {
5893
guard expected > 0 else { return 0 }
59-
return min(1, (Double(finished) + currentItemFraction) / Double(expected))
94+
return min(1, (Double(playIndex) + currentItemFraction) / Double(expected))
6095
}
6196

6297
private var currentItemFraction: Double {

‎Sources/UI/PlayerOverlay.swift‎

Lines changed: 35 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,54 @@
11
import SwiftUI
22

3-
/// Compact floating transport shown while synthesizing / playing.
3+
/// Compact floating transport shown while synthesizing / playing. Shows WHAT is
4+
/// playing (TTS vs 해설) rather than the script text, with standard paragraph
5+
/// navigation.
46
struct PlayerOverlay: View {
57
@ObservedObject var app: AppState
68

9+
private var tint: Color { app.playbackMode == .tts ? .blue : .purple }
10+
711
var body: some View {
8-
HStack(spacing: 12) {
9-
Group {
12+
VStack(alignment: .leading, spacing: 8) {
13+
HStack(spacing: 6) {
14+
Label(app.playbackMode.label, systemImage: app.playbackMode.icon)
15+
.font(.caption.weight(.semibold))
16+
.padding(.horizontal, 8).padding(.vertical, 3)
17+
.background(tint.opacity(0.18), in: Capsule())
18+
.foregroundStyle(tint)
19+
if app.chunkCount > 1 {
20+
Text("문단 \(app.chunkIndex)/\(app.chunkCount)")
21+
.font(.caption).foregroundStyle(.secondary)
22+
}
23+
Spacer()
1024
if app.phase == .synthesizing {
11-
ProgressView().controlSize(.small).frame(width: 22)
12-
} else {
13-
Button { app.togglePause() } label: {
14-
Image(systemName: app.phase == .paused ? "play.fill" : "pause.fill")
15-
.font(.system(size: 16, weight: .semibold))
16-
.frame(width: 22)
17-
}
18-
.buttonStyle(.plain)
19-
.help(app.phase == .paused ? "재개" : "일시정지")
25+
ProgressView().controlSize(.small)
26+
Text("합성 중…").font(.caption).foregroundStyle(.secondary)
2027
}
2128
}
2229

23-
VStack(alignment: .leading, spacing: 5) {
24-
HStack(spacing: 6) {
25-
Text(app.currentText.isEmpty ? "Codebasic TTS" : app.currentText)
26-
.lineLimit(1).font(.callout)
27-
if app.chunkCount > 1 {
28-
Text("· 문단 \(app.chunkIndex)/\(app.chunkCount)")
29-
.font(.caption).foregroundStyle(.secondary).fixedSize()
30-
}
30+
HStack(spacing: 16) {
31+
Button { app.skipPrev() } label: { Image(systemName: "backward.fill") }
32+
.disabled(!app.canSkipPrev)
33+
Button { app.togglePause() } label: {
34+
Image(systemName: app.phase == .paused ? "play.fill" : "pause.fill")
35+
.font(.system(size: 18, weight: .semibold)).frame(width: 22)
3136
}
37+
.disabled(app.phase == .synthesizing)
38+
.help(app.phase == .paused ? "재개" : "일시정지")
39+
Button { app.skipNext() } label: { Image(systemName: "forward.fill") }
40+
.disabled(!app.canSkipNext)
41+
3242
ProgressView(value: app.progress).progressViewStyle(.linear)
33-
}
3443

35-
Button { app.stop() } label: {
36-
Image(systemName: "stop.fill").font(.system(size: 15, weight: .semibold))
44+
Button { app.stop() } label: { Image(systemName: "stop.fill") }
45+
.foregroundStyle(.secondary).help("중지")
3746
}
3847
.buttonStyle(.plain)
39-
.foregroundStyle(.secondary)
40-
.help("중지")
48+
.font(.system(size: 14, weight: .semibold))
4149
}
42-
.padding(.horizontal, 16)
43-
.padding(.vertical, 12)
44-
.frame(width: 340)
50+
.padding(.horizontal, 16).padding(.vertical, 12)
51+
.frame(width: 360)
4552
.background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 14))
4653
.overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(.white.opacity(0.08)))
4754
}

0 commit comments

Comments
 (0)