ActiveRecordingView.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. import SwiftUI
  2. import SwiftData
  3. // MARK: - ActiveRecordingView
  4. /// The live recording screen showing real-time waveform, elapsed time,
  5. /// and quick-action buttons for adding photos and notes during a session.
  6. /// Fully redesigned to use a minimalist business-focused line-drawn UI.
  7. struct ActiveRecordingView: View {
  8. @Environment(\.modelContext) private var modelContext
  9. @Environment(\.dismiss) private var dismiss
  10. let session: CelestiaSession
  11. var initialDuration: TimeInterval = 0
  12. let recordingSource: RecordingSourceChoice
  13. var onFinishRecording: (() -> Void)? = nil
  14. @State private var recordingVM: RecordingViewModel
  15. @State private var showNoteSheet = false
  16. @State private var showCamera = false
  17. @State private var noteText = ""
  18. @State private var latestEvent: CelestiaTimelineEvent?
  19. @State private var latestEventVisible = false
  20. @State private var isEndingRecording = false
  21. @State private var stopErrorMessage: String?
  22. @State private var recordName: String
  23. @State private var showRecordNameEditor = false
  24. @FocusState private var isRecordNameFocused: Bool
  25. init(
  26. session: CelestiaSession,
  27. initialDuration: TimeInterval = 0,
  28. recordingSource: RecordingSourceChoice = .iPhone,
  29. onFinishRecording: (() -> Void)? = nil
  30. ) {
  31. self.session = session
  32. self.initialDuration = initialDuration
  33. self.recordingSource = recordingSource
  34. self.onFinishRecording = onFinishRecording
  35. _recordingVM = State(initialValue: RecordingViewModel(source: recordingSource))
  36. _recordName = State(initialValue: session.title)
  37. }
  38. var body: some View {
  39. ZStack(alignment: .top) {
  40. // Dynamic clean background
  41. Color.spaceBlack
  42. .ignoresSafeArea()
  43. VStack(spacing: 0) {
  44. recordNameSection
  45. .padding(.horizontal, 24)
  46. .padding(.top, 16)
  47. .padding(.bottom, 14)
  48. // Top Header Block (Timecode + Indicator)
  49. VStack(spacing: 16) {
  50. timecodeSection
  51. recordingIndicator
  52. }
  53. .padding(.bottom, 24)
  54. // Live Waveform
  55. waveformSection
  56. .padding(.horizontal, 24)
  57. .padding(.bottom, 20)
  58. // Latest Event Card
  59. latestEventCard
  60. .padding(.horizontal, 24)
  61. .padding(.bottom, 20)
  62. Spacer()
  63. // Action Buttons
  64. actionButtons
  65. .padding(.horizontal, 48)
  66. .padding(.bottom, 32)
  67. // End Recording
  68. endRecordingButton
  69. .padding(.bottom, 24)
  70. }
  71. .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
  72. .ignoresSafeArea(.keyboard, edges: .bottom)
  73. }
  74. .ignoresSafeArea(.keyboard, edges: .bottom)
  75. .toolbar(.hidden, for: .tabBar)
  76. .toolbar(.hidden, for: .navigationBar)
  77. .navigationBarHidden(true)
  78. .navigationBarBackButtonHidden(true)
  79. .sheet(isPresented: $showRecordNameEditor) {
  80. recordNameEditorSheet
  81. }
  82. .sheet(isPresented: $showNoteSheet) {
  83. noteInputSheet
  84. }
  85. .fullScreenCover(isPresented: $showCamera) {
  86. ImagePicker(sourceType: UIImagePickerController.isSourceTypeAvailable(.camera) ? .camera : .photoLibrary) { image in
  87. saveImageAndAddEvent(image)
  88. }
  89. }
  90. .onAppear {
  91. UIApplication.shared.isIdleTimerDisabled = true
  92. recordingVM.startRecording(initialDuration: initialDuration)
  93. }
  94. .onDisappear {
  95. UIApplication.shared.isIdleTimerDisabled = false
  96. commitRecordName()
  97. if recordingVM.isRecording {
  98. recordingVM.stopRecording()
  99. }
  100. }
  101. .alert("无法结束设备录音", isPresented: Binding(
  102. get: { stopErrorMessage != nil },
  103. set: { if !$0 { stopErrorMessage = nil } }
  104. )) {
  105. Button("重试") { endRecording() }
  106. Button("继续录音", role: .cancel) { stopErrorMessage = nil }
  107. } message: {
  108. Text(stopErrorMessage ?? "请确认微光仍在附近并保持连接。")
  109. }
  110. }
  111. // MARK: - Record Name
  112. private var recordNameSection: some View {
  113. Button {
  114. recordName = session.title
  115. showRecordNameEditor = true
  116. } label: {
  117. VStack(alignment: .leading, spacing: 8) {
  118. HStack(spacing: 6) {
  119. Text("记录名称")
  120. .font(.system(size: 10, weight: .semibold, design: .monospaced))
  121. .tracking(1.4)
  122. Spacer()
  123. Image(systemName: "pencil")
  124. .font(.system(size: 11, weight: .semibold))
  125. }
  126. .foregroundStyle(Color.secondary)
  127. Text(session.title)
  128. .font(.system(size: 19, weight: .semibold))
  129. .foregroundStyle(Color.primary)
  130. .lineLimit(1)
  131. .frame(maxWidth: .infinity, alignment: .leading)
  132. Rectangle()
  133. .fill(Color.primary.opacity(0.16))
  134. .frame(height: 1)
  135. }
  136. .padding(.horizontal, 14)
  137. .padding(.vertical, 12)
  138. .background(Color.cardBackground.opacity(0.45))
  139. .businessBorder(cornerRadius: 8)
  140. .contentShape(Rectangle())
  141. }
  142. .buttonStyle(.plain)
  143. }
  144. private var recordNameEditorSheet: some View {
  145. NavigationStack {
  146. ZStack {
  147. Color.spaceBlack.ignoresSafeArea()
  148. VStack(alignment: .leading, spacing: 10) {
  149. Text("记录名称")
  150. .font(.system(size: 10, weight: .semibold, design: .monospaced))
  151. .foregroundStyle(Color.secondary)
  152. .tracking(1.4)
  153. TextField("输入记录名称", text: $recordName)
  154. .focused($isRecordNameFocused)
  155. .font(.system(size: 18, weight: .semibold))
  156. .foregroundStyle(Color.primary)
  157. .textInputAutocapitalization(.never)
  158. .autocorrectionDisabled()
  159. .submitLabel(.done)
  160. .padding(.horizontal, 14)
  161. .padding(.vertical, 12)
  162. .background(Color.cardBackground.opacity(0.5))
  163. .businessBorder(cornerRadius: 8)
  164. .onSubmit {
  165. saveRecordNameAndCloseEditor()
  166. }
  167. Spacer()
  168. }
  169. .padding(20)
  170. }
  171. .navigationTitle("修改记录名称")
  172. .navigationBarTitleDisplayMode(.inline)
  173. .toolbar {
  174. ToolbarItem(placement: .cancellationAction) {
  175. Button("取消") {
  176. recordName = session.title
  177. showRecordNameEditor = false
  178. }
  179. .foregroundStyle(Color.secondary)
  180. }
  181. ToolbarItem(placement: .confirmationAction) {
  182. Button("保存") {
  183. saveRecordNameAndCloseEditor()
  184. }
  185. .disabled(recordName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
  186. }
  187. }
  188. }
  189. .presentationDetents([.height(190)])
  190. .presentationDragIndicator(.visible)
  191. .presentationBackground(Color.spaceBlack)
  192. .onAppear {
  193. DispatchQueue.main.async {
  194. isRecordNameFocused = true
  195. }
  196. }
  197. }
  198. // MARK: - Timecode
  199. private var timecodeSection: some View {
  200. Text(recordingVM.elapsedTimeFormatted)
  201. .font(.system(size: 52, weight: .light))
  202. .monospacedDigit()
  203. .foregroundStyle(Color.primary)
  204. .contentTransition(.numericText(countsDown: false))
  205. .frame(height: 64)
  206. }
  207. // MARK: - Recording Indicator
  208. private var recordingIndicator: some View {
  209. VStack(spacing: 8) {
  210. HStack(spacing: 8) {
  211. TimelineView(.periodic(from: .now, by: 1.0)) { context in
  212. let isEven = Int(context.date.timeIntervalSince1970) % 2 == 0
  213. Circle()
  214. .fill(recordingVM.isRecording ? Color.recordingRed : Color.secondary)
  215. .frame(width: 8, height: 8)
  216. .opacity(recordingVM.isRecording ? (isEven ? 1.0 : 0.3) : 0.6)
  217. .animation(.easeInOut(duration: 0.5), value: isEven)
  218. }
  219. .frame(width: 10, height: 10)
  220. Text(recordingVM.isPaused ? "已暂停" : recordingVM.statusMessage)
  221. .font(.system(size: 11, weight: .semibold, design: .monospaced))
  222. .foregroundStyle(recordingVM.isRecording ? Color.recordingRed : Color.secondary)
  223. .tracking(1.2)
  224. }
  225. HStack(spacing: 6) {
  226. Image(systemName: recordingSource.systemImage)
  227. .font(.system(size: 11, weight: .medium))
  228. Text("当前录音设备:\(recordingVM.sourceDisplayName)")
  229. .font(.system(size: 11, weight: .medium))
  230. }
  231. .foregroundStyle(Color.primary.opacity(0.85))
  232. if let error = recordingVM.errorMessage {
  233. Text(error)
  234. .font(.system(size: 10))
  235. .foregroundStyle(Color.recordingRed)
  236. .multilineTextAlignment(.center)
  237. .lineLimit(2)
  238. }
  239. }
  240. .padding(.horizontal, 10)
  241. .padding(.vertical, 8)
  242. .businessBorder(cornerRadius: 6)
  243. }
  244. // MARK: - Waveform
  245. private var waveformSection: some View {
  246. VStack(spacing: 0) {
  247. LiveWaveformView(samples: recordingVM.waveformSamples)
  248. .frame(height: 90)
  249. // Graphical VU Meter + Numeric Display
  250. HStack(spacing: 10) {
  251. AmplitudeLevelMeterView(amplitude: recordingVM.currentAmplitude)
  252. Spacer(minLength: 0)
  253. Text(String(format: "%02.0f%%", recordingVM.currentAmplitude * 100))
  254. .font(.system(size: 9, weight: .medium, design: .monospaced))
  255. .foregroundStyle(recordingVM.currentAmplitude > 0.85 ? Color.recordingRed : Color.secondary)
  256. }
  257. .padding(.horizontal, 4)
  258. .padding(.top, 10)
  259. }
  260. .frame(height: 114)
  261. }
  262. // MARK: - Latest Event Card
  263. private var latestEventCard: some View {
  264. ZStack { // Fix: Use ZStack instead of Group to enforce the fixed frame even when empty
  265. if let event = latestEvent, latestEventVisible {
  266. HStack(spacing: 12) {
  267. Image(systemName: event.eventIcon)
  268. .font(.system(size: 12))
  269. .foregroundStyle(Color.primary)
  270. .frame(width: 28, height: 28)
  271. .businessBorder(cornerRadius: 14)
  272. VStack(alignment: .leading, spacing: 2) {
  273. Text(eventLabel(for: event.eventType))
  274. .font(.system(size: 11, weight: .semibold))
  275. .foregroundStyle(Color.primary)
  276. if let text = event.textContent {
  277. Text(text)
  278. .font(.system(size: 12))
  279. .foregroundStyle(Color.secondary)
  280. .lineLimit(1)
  281. }
  282. }
  283. Spacer()
  284. Text(event.relativeTimeFormatted)
  285. .font(.system(size: 11, weight: .regular, design: .monospaced))
  286. .foregroundStyle(Color.secondary)
  287. }
  288. .padding(12)
  289. .background(Color.cardBackground.opacity(0.4))
  290. .businessBorder(cornerRadius: 8)
  291. .transition(.asymmetric(
  292. insertion: .move(edge: .bottom).combined(with: .opacity),
  293. removal: .opacity
  294. ))
  295. }
  296. }
  297. .frame(height: 56)
  298. .animation(.spring(response: 0.35, dampingFraction: 0.8), value: latestEvent?.id)
  299. }
  300. // MARK: - Action Buttons
  301. private var actionButtons: some View {
  302. HStack(spacing: 40) {
  303. // Camera button
  304. actionButton(
  305. icon: "camera",
  306. label: "拍照打点"
  307. ) {
  308. capturePhoto()
  309. }
  310. // Note button
  311. actionButton(
  312. icon: "doc.text",
  313. label: "文字笔记"
  314. ) {
  315. showNoteSheet = true
  316. }
  317. }
  318. }
  319. private func actionButton(
  320. icon: String,
  321. label: String,
  322. action: @escaping () -> Void
  323. ) -> some View {
  324. Button(action: action) {
  325. VStack(spacing: 10) {
  326. ZStack {
  327. Circle()
  328. .fill(Color.primary.opacity(0.02))
  329. .frame(width: 60, height: 60)
  330. .businessBorder(cornerRadius: 30)
  331. Image(systemName: icon)
  332. .font(.system(size: 20, weight: .light))
  333. .foregroundStyle(Color.primary)
  334. }
  335. Text(label)
  336. .font(.system(size: 11, weight: .regular))
  337. .foregroundStyle(Color.secondary)
  338. }
  339. }
  340. .buttonStyle(.plain)
  341. }
  342. // MARK: - End Recording Button
  343. private var endRecordingButton: some View {
  344. Button {
  345. endRecording()
  346. } label: {
  347. VStack(spacing: 6) {
  348. Text("双击结束录制")
  349. .font(.system(size: 13, weight: .medium))
  350. .foregroundStyle(Color.recordingRed)
  351. .padding(.horizontal, 24)
  352. .padding(.vertical, 10)
  353. .businessBorder(cornerRadius: 8)
  354. Text("双击即可完成本次现场录音")
  355. .font(.system(size: 8, weight: .medium, design: .monospaced))
  356. .foregroundStyle(Color.secondary.opacity(0.5))
  357. .tracking(1.5)
  358. }
  359. }
  360. .highPriorityGesture(
  361. TapGesture(count: 2).onEnded {
  362. endRecording()
  363. }
  364. )
  365. .buttonStyle(.plain)
  366. .disabled(isEndingRecording)
  367. }
  368. // MARK: - Note Input Sheet
  369. private var noteInputSheet: some View {
  370. NavigationStack {
  371. ZStack {
  372. Color.spaceBlack.ignoresSafeArea()
  373. VStack(spacing: 20) {
  374. TextField("输入笔记内容...", text: $noteText, axis: .vertical)
  375. .textFieldStyle(.plain)
  376. .font(.system(size: 15))
  377. .foregroundStyle(Color.primary)
  378. .padding(14)
  379. .frame(minHeight: 120, alignment: .top)
  380. .background(Color.cardBackground.opacity(0.5))
  381. .businessBorder(cornerRadius: 8)
  382. Button {
  383. addNote()
  384. } label: {
  385. Text("保存笔记")
  386. .font(.system(size: 14, weight: .semibold))
  387. .foregroundStyle(Color.spaceBlack)
  388. .frame(maxWidth: .infinity)
  389. .padding(.vertical, 12)
  390. .background(Color.primary)
  391. .cornerRadius(8)
  392. }
  393. .disabled(noteText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
  394. Spacer()
  395. }
  396. .padding(24)
  397. }
  398. .navigationTitle("添加笔记")
  399. .navigationBarTitleDisplayMode(.inline)
  400. .toolbar {
  401. ToolbarItem(placement: .cancellationAction) {
  402. Button("取消") {
  403. showNoteSheet = false
  404. noteText = ""
  405. }
  406. .foregroundStyle(Color.secondary)
  407. }
  408. }
  409. }
  410. .presentationDetents([.medium])
  411. .presentationDragIndicator(.visible)
  412. .presentationBackground(Color.spaceBlack)
  413. }
  414. // MARK: - Actions
  415. private func capturePhoto() {
  416. showCamera = true
  417. }
  418. private func saveImageAndAddEvent(_ image: UIImage) {
  419. guard let data = image.jpegData(compressionQuality: 0.8) else { return }
  420. let filename = "photo_\(UUID().uuidString).jpg"
  421. let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
  422. let fileURL = documentsURL.appendingPathComponent(filename)
  423. do {
  424. try data.write(to: fileURL)
  425. let event = recordingVM.addPhotoEvent(to: session, localFilePath: filename)
  426. HapticManager.trigger(.photoCapture)
  427. showLatestEvent(event)
  428. } catch {
  429. print("[ActiveRecordingView] Failed to save captured photo: \(error.localizedDescription)")
  430. }
  431. }
  432. private func addNote() {
  433. let text = noteText.trimmingCharacters(in: .whitespacesAndNewlines)
  434. guard !text.isEmpty else { return }
  435. let event = recordingVM.addNoteEvent(to: session, text: text)
  436. HapticManager.trigger(.noteAdded)
  437. showLatestEvent(event)
  438. noteText = ""
  439. showNoteSheet = false
  440. }
  441. private func endRecording() {
  442. guard !isEndingRecording else { return }
  443. commitRecordName()
  444. isEndingRecording = true
  445. recordingVM.stopRecording { result in
  446. switch result {
  447. case .success(let confirmedURL):
  448. finalizeRecording(newRecordedURL: confirmedURL ?? recordingVM.outputFileURL)
  449. case .failure(let error):
  450. isEndingRecording = false
  451. stopErrorMessage = error.localizedDescription
  452. }
  453. }
  454. }
  455. private func finalizeRecording(newRecordedURL: URL?) {
  456. let existingPath = session.localAudioPath
  457. let existingURL = AudioPathHelper.resolveURL(for: existingPath)
  458. let totalRecordedSeconds = recordingVM.elapsedTime
  459. if let newRecordedURL = newRecordedURL {
  460. Task { @MainActor in
  461. let mergedURL = await AudioMerger.mergeAudioFiles(firstURL: existingURL, secondURL: newRecordedURL)
  462. session.localAudioPath = AudioPathHelper.relativePath(from: mergedURL.path)
  463. session.endTime = session.startTime.addingTimeInterval(totalRecordedSeconds)
  464. try? modelContext.save()
  465. HapticManager.trigger(.recordStop)
  466. isEndingRecording = false
  467. dismiss()
  468. onFinishRecording?()
  469. }
  470. } else {
  471. if existingURL != nil {
  472. session.endTime = session.startTime.addingTimeInterval(totalRecordedSeconds)
  473. try? modelContext.save()
  474. } else {
  475. session.endTime = Date()
  476. try? modelContext.save()
  477. }
  478. HapticManager.trigger(.recordStop)
  479. isEndingRecording = false
  480. dismiss()
  481. onFinishRecording?()
  482. }
  483. }
  484. private func showLatestEvent(_ event: CelestiaTimelineEvent) {
  485. withAnimation {
  486. latestEvent = event
  487. latestEventVisible = true
  488. }
  489. // Auto-dismiss after a few seconds
  490. DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
  491. withAnimation {
  492. latestEventVisible = false
  493. }
  494. }
  495. }
  496. // MARK: - Helpers
  497. private func eventLabel(for type: String) -> String {
  498. switch type {
  499. case "PHOTO": return "已捕获照片"
  500. case "NOTE": return "已保存笔记"
  501. case "MARKER": return "标记点"
  502. case "VOICE": return "音轨事件"
  503. default: return "事件"
  504. }
  505. }
  506. private func commitRecordName() {
  507. let trimmedName = recordName.trimmingCharacters(in: .whitespacesAndNewlines)
  508. if trimmedName.isEmpty {
  509. recordName = session.title
  510. return
  511. }
  512. guard session.title != trimmedName else {
  513. if recordName != trimmedName {
  514. recordName = trimmedName
  515. }
  516. return
  517. }
  518. recordName = trimmedName
  519. session.title = trimmedName
  520. session.isSynced = false
  521. session.syncState = .pending
  522. try? modelContext.save()
  523. }
  524. private func saveRecordNameAndCloseEditor() {
  525. commitRecordName()
  526. guard !recordName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
  527. isRecordNameFocused = false
  528. showRecordNameEditor = false
  529. }
  530. }
  531. // MARK: - Amplitude Level Meter View
  532. /// A minimalist graphical VU meter bar visualizing real-time audio amplitude.
  533. private struct AmplitudeLevelMeterView: View {
  534. let amplitude: Float // 0.0 to 1.0
  535. private let totalSegments: Int = 16
  536. var body: some View {
  537. HStack(spacing: 3) {
  538. ForEach(0..<totalSegments, id: \.self) { index in
  539. let threshold = Float(index) / Float(totalSegments)
  540. let isFilled = amplitude > threshold
  541. let isPeak = index >= totalSegments - 2
  542. RoundedRectangle(cornerRadius: 1)
  543. .fill(
  544. isFilled
  545. ? (isPeak ? Color.recordingRed : Color.primary.opacity(0.85))
  546. : Color.primary.opacity(0.12)
  547. )
  548. .frame(height: isFilled ? (isPeak ? 7 : 5) : 3)
  549. .animation(.spring(response: 0.15, dampingFraction: 0.75), value: amplitude)
  550. }
  551. }
  552. }
  553. }
  554. // MARK: - Preview
  555. #Preview {
  556. let session = CelestiaSession(title: "Preview Session")
  557. ActiveRecordingView(session: session)
  558. .modelContainer(for: CelestiaSession.self, inMemory: true)
  559. }