useAudioPlayer.ts 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import { ref, onUnmounted, type Ref } from 'vue'
  2. import { synthesize } from '../services/speechService'
  3. export type PlaySource =
  4. | { kind: 'tts'; text: string }
  5. | { kind: 'blob'; blob: Blob }
  6. export interface AudioPlayer {
  7. /** Id of the message currently playing (audio element fired `playing`). */
  8. playingId: Readonly<Ref<string | null>>
  9. /** Id of the message whose synthesis or play() is in flight. */
  10. loadingId: Readonly<Ref<string | null>>
  11. /** Id of the message whose last playback attempt failed. Sticky until next play(). */
  12. errorId: Readonly<Ref<string | null>>
  13. play(id: string, source: PlaySource): Promise<void>
  14. stop(): void
  15. }
  16. /**
  17. * Single audio playback owner for the dialogue view.
  18. *
  19. * Structural guarantees:
  20. * - At most one HTMLAudioElement / one in-flight synthesis at a time.
  21. * Every play() begins by aborting & pausing the prior session.
  22. * - Cached MP3 blobs (one per AI messageId) live in-memory; URLs are
  23. * revoked on view unmount.
  24. * - Errors collapse to a single per-id state. The view renders a retry
  25. * affordance; clicking the same play button re-enters play().
  26. */
  27. export function useAudioPlayer(): AudioPlayer {
  28. const playingId = ref<string | null>(null)
  29. const loadingId = ref<string | null>(null)
  30. const errorId = ref<string | null>(null)
  31. // Closure-private state. Not reactive on purpose.
  32. let currentAudio: HTMLAudioElement | null = null
  33. let synthAbort: AbortController | null = null
  34. const ttsCache = new Map<string, Blob>()
  35. const cachedUrls: string[] = []
  36. function clearCurrentAudio() {
  37. if (currentAudio) {
  38. currentAudio.onplaying = null
  39. currentAudio.onended = null
  40. currentAudio.onerror = null
  41. try { currentAudio.pause() } catch { /* ignore */ }
  42. currentAudio = null
  43. }
  44. }
  45. function failPlayback(id: string, reason: unknown) {
  46. if (loadingId.value === id) loadingId.value = null
  47. if (playingId.value === id) playingId.value = null
  48. errorId.value = id
  49. console.warn('[audio-player] playback failed:', id, reason)
  50. }
  51. async function play(id: string, source: PlaySource): Promise<void> {
  52. // A fresh attempt — drop stale error.
  53. errorId.value = null
  54. // Abort any in-flight synthesis and pause any current audio.
  55. stop()
  56. loadingId.value = id
  57. try {
  58. let blob: Blob
  59. if (source.kind === 'blob') {
  60. blob = source.blob
  61. }
  62. else {
  63. const cached = ttsCache.get(id)
  64. if (cached) {
  65. blob = cached
  66. }
  67. else {
  68. synthAbort = new AbortController()
  69. blob = await synthesize(source.text, synthAbort.signal)
  70. synthAbort = null
  71. // We may have been interrupted while awaiting (loadingId changed).
  72. if (loadingId.value !== id) return
  73. ttsCache.set(id, blob)
  74. }
  75. }
  76. const url = URL.createObjectURL(blob)
  77. cachedUrls.push(url)
  78. const audio = new Audio(url)
  79. currentAudio = audio
  80. audio.onplaying = () => {
  81. if (loadingId.value === id) loadingId.value = null
  82. playingId.value = id
  83. }
  84. audio.onended = () => {
  85. if (currentAudio === audio) currentAudio = null
  86. if (playingId.value === id) playingId.value = null
  87. }
  88. audio.onerror = () => {
  89. if (currentAudio === audio) currentAudio = null
  90. failPlayback(id, audio.error)
  91. }
  92. try {
  93. await audio.play()
  94. }
  95. catch (err) {
  96. // Most often: autoplay policy blocked the call.
  97. if (currentAudio === audio) currentAudio = null
  98. failPlayback(id, err)
  99. }
  100. }
  101. catch (err) {
  102. // Synthesis path errors. AbortError fires when stop() was called
  103. // mid-synthesis — that is a normal interrupt, not a failure.
  104. synthAbort = null
  105. if (err instanceof Error && err.name === 'AbortError') {
  106. // loadingId was already cleared synchronously by stop(); if a newer
  107. // play() has since set it again, that value belongs to that call,
  108. // not this aborted one. Do nothing here.
  109. return
  110. }
  111. failPlayback(id, err)
  112. }
  113. }
  114. function stop(): void {
  115. if (synthAbort) {
  116. synthAbort.abort()
  117. synthAbort = null
  118. }
  119. clearCurrentAudio()
  120. loadingId.value = null
  121. playingId.value = null
  122. // Note: errorId is intentionally left alone here. It is only
  123. // cleared at the start of a new play() attempt.
  124. }
  125. onUnmounted(() => {
  126. stop()
  127. for (const url of cachedUrls) {
  128. try { URL.revokeObjectURL(url) } catch { /* ignore */ }
  129. }
  130. cachedUrls.length = 0
  131. ttsCache.clear()
  132. })
  133. return {
  134. playingId,
  135. loadingId,
  136. errorId,
  137. play,
  138. stop,
  139. }
  140. }