Line data Source code
1 : import { reportError } from '@comfyorg/telemetry/reportError'
2 : import type { Surface } from '@comfyorg/telemetry/reportError'
3 : import { tryOnScopeDispose, useMediaControls, whenever } from '@vueuse/core'
4 : import { computed, ref, watch } from 'vue'
5 : import type { Ref } from 'vue'
6 :
7 : import { useToast } from '@/components/ui/toast/toastStore'
8 : import { t } from '@/i18n'
9 : import { api } from '@/scripts/api'
10 : import { createToastId } from '@/types/toastId'
11 : import { formatTime } from '@/utils/formatUtil'
12 : import { reloadFailedMedia } from '@/utils/mediaReloadUtil'
13 :
14 : interface WaveformBar {
15 : height: number
16 : }
17 :
18 : interface UseWaveAudioPlayerOptions {
19 : src: Readonly<Ref<string | undefined>>
20 : logicalSrc?: Readonly<Ref<string | undefined>>
21 : surface?: Surface
22 : barCount?: number
23 : waveform?: boolean
24 : }
25 :
26 2 : export function useWaveAudioPlayer(options: UseWaveAudioPlayerOptions) {
27 2 : const {
28 : src,
29 : logicalSrc = src,
30 : surface = 'assets',
31 : barCount = 40,
32 : waveform = true
33 : } = options
34 :
35 2 : const audioRef = ref<HTMLAudioElement>()
36 2 : const waveformRef = ref<HTMLElement>()
37 2 : const loading = ref(false)
38 2 : let decodeRequestId = 0
39 2 : const bars = ref<WaveformBar[]>(generatePlaceholderBars())
40 :
41 2 : const toast = useToast()
42 2 : const playbackErrorToastId = createToastId()
43 2 : let playAttempt = 0
44 :
45 2 : const { playing, currentTime, duration, volume, muted } =
46 : useMediaControls(audioRef)
47 :
48 1 : function invalidatePlayback() {
49 1 : playAttempt++
50 1 : toast.dismiss(playbackErrorToastId)
51 : }
52 :
53 2 : tryOnScopeDispose(invalidatePlayback)
54 2 : watch(logicalSrc, invalidatePlayback)
55 :
56 2 : const playedBarIndex = computed(() => {
57 2 : if (duration.value === 0) return -1
58 0 : return Math.floor((currentTime.value / duration.value) * barCount) - 1
59 : })
60 :
61 2 : const formattedCurrentTime = computed(() => formatTime(currentTime.value))
62 2 : const formattedDuration = computed(() => formatTime(duration.value))
63 :
64 4 : function generatePlaceholderBars(): WaveformBar[] {
65 4 : return Array.from({ length: barCount }, () => ({
66 : height: Math.random() * 60 + 10
67 : }))
68 : }
69 :
70 0 : function generateBarsFromBuffer(buffer: AudioBuffer) {
71 0 : const channelData = buffer.getChannelData(0)
72 0 : if (channelData.length === 0) {
73 0 : bars.value = generatePlaceholderBars()
74 0 : return
75 : }
76 :
77 0 : const averages: number[] = []
78 0 : for (let i = 0; i < barCount; i++) {
79 0 : const start = Math.floor((i * channelData.length) / barCount)
80 0 : const end = Math.max(
81 : start + 1,
82 : Math.floor(((i + 1) * channelData.length) / barCount)
83 : )
84 0 : let sum = 0
85 0 : for (let j = start; j < end && j < channelData.length; j++) {
86 0 : sum += Math.abs(channelData[j])
87 : }
88 0 : averages.push(sum / (end - start))
89 : }
90 :
91 0 : const peak = Math.max(...averages) || 1
92 0 : bars.value = averages.map((avg) => ({
93 : height: Math.max(8, (avg / peak) * 100)
94 : }))
95 : }
96 :
97 2 : async function decodeAudioSource(url: string) {
98 2 : const requestId = ++decodeRequestId
99 2 : loading.value = true
100 2 : let ctx: AudioContext | undefined
101 2 : try {
102 2 : const apiBase = api.apiURL('/')
103 2 : const route = url.includes(apiBase)
104 : ? url.slice(url.indexOf(apiBase) + api.apiURL('').length)
105 : : url
106 2 : const response = await api.fetchApi(route)
107 2 : if (requestId !== decodeRequestId) return
108 2 : if (!response.ok) {
109 2 : console.error(`Failed to fetch audio (${response.status})`)
110 2 : if (requestId === decodeRequestId) {
111 2 : bars.value = generatePlaceholderBars()
112 : }
113 2 : return
114 : }
115 0 : const arrayBuffer = await response.arrayBuffer()
116 :
117 0 : if (requestId !== decodeRequestId) return
118 :
119 0 : ctx = new AudioContext()
120 0 : const audioBuffer = await ctx.decodeAudioData(arrayBuffer)
121 0 : if (requestId !== decodeRequestId) return
122 0 : generateBarsFromBuffer(audioBuffer)
123 : } catch {
124 0 : if (requestId === decodeRequestId) {
125 0 : bars.value = generatePlaceholderBars()
126 : }
127 : } finally {
128 2 : await ctx?.close()
129 2 : if (requestId === decodeRequestId) {
130 2 : loading.value = false
131 : }
132 : }
133 : }
134 :
135 2 : const progressRatio = computed(() => {
136 0 : if (duration.value === 0) return 0
137 0 : return (currentTime.value / duration.value) * 100
138 : })
139 :
140 0 : async function startPlayback() {
141 0 : const audio = audioRef.value
142 0 : if (!audio) return
143 :
144 0 : const attempt = ++playAttempt
145 0 : try {
146 0 : if (audio.error) reloadFailedMedia(audio)
147 0 : await audio.play()
148 0 : if (attempt === playAttempt) toast.dismiss(playbackErrorToastId)
149 : } catch (error) {
150 0 : if (attempt !== playAttempt) return
151 0 : audio.pause()
152 0 : playing.value = false
153 0 : if (error instanceof DOMException && error.name === 'AbortError') {
154 0 : toast.dismiss(playbackErrorToastId)
155 0 : return
156 : }
157 0 : reportError(error, {
158 : errorType: 'error_playing_audio',
159 : surface,
160 : level: 'warning'
161 : })
162 0 : toast.error(t('g.error'), {
163 : id: playbackErrorToastId,
164 : description: t('g.audioPlaybackFailed')
165 : })
166 : }
167 : }
168 :
169 0 : function togglePlayPause() {
170 0 : const audio = audioRef.value
171 0 : if (!audio) return
172 :
173 0 : if (audio.paused) {
174 0 : void startPlayback()
175 0 : return
176 : }
177 0 : invalidatePlayback()
178 0 : audio.pause()
179 : }
180 :
181 0 : function seekToStart() {
182 0 : currentTime.value = 0
183 : }
184 :
185 0 : function seekToEnd() {
186 0 : currentTime.value = duration.value
187 0 : playing.value = false
188 : }
189 :
190 0 : function seekToRatio(ratio: number) {
191 : const clamped = Math.max(0, Math.min(1, ratio))
192 0 : currentTime.value = clamped * duration.value
193 : }
194 :
195 0 : function toggleMute() {
196 0 : muted.value = !muted.value
197 : }
198 :
199 2 : const volumeIcon = computed(() => {
200 0 : if (muted.value || volume.value === 0) return 'icon-[lucide--volume-x]'
201 0 : if (volume.value < 0.5) return 'icon-[lucide--volume-1]'
202 0 : return 'icon-[lucide--volume-2]'
203 : })
204 :
205 0 : function handleWaveformClick(event: MouseEvent) {
206 0 : if (!waveformRef.value || duration.value === 0) return
207 0 : const rect = waveformRef.value.getBoundingClientRect()
208 0 : const ratio = Math.max(
209 : 0,
210 : Math.min(1, (event.clientX - rect.left) / rect.width)
211 : )
212 0 : currentTime.value = ratio * duration.value
213 :
214 0 : if (audioRef.value?.paused) void startPlayback()
215 : }
216 :
217 2 : whenever(
218 : src,
219 : (url) => {
220 2 : playing.value = false
221 2 : currentTime.value = 0
222 2 : if (waveform) void decodeAudioSource(url)
223 : },
224 : { immediate: true }
225 : )
226 :
227 2 : return {
228 : audioRef,
229 : waveformRef,
230 : bars,
231 : loading,
232 : isPlaying: playing,
233 : playedBarIndex,
234 : progressRatio,
235 : formattedCurrentTime,
236 : formattedDuration,
237 : togglePlayPause,
238 : seekToStart,
239 : seekToEnd,
240 : volume,
241 : muted,
242 : volumeIcon,
243 : toggleMute,
244 : seekToRatio,
245 : handleWaveformClick
246 : }
247 : }
|