forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAudioPlayer.tsx
More file actions
362 lines (325 loc) · 11.2 KB
/
Copy pathAudioPlayer.tsx
File metadata and controls
362 lines (325 loc) · 11.2 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
'use client';
import {
useState,
useRef,
useEffect,
useCallback,
useImperativeHandle,
forwardRef,
} from 'react';
import { Play, Pause, Volume2, VolumeX, Loader2, Download } from 'lucide-react';
import { cn } from '@/lib/utils';
import { getConversationAudioUrlsWithPoll } from '@/lib/api';
import type { AudioFileUrlInfo } from '@/types/conversation';
interface AudioPlayerProps {
conversationId: string;
audioFiles: AudioFileUrlInfo[];
onTimeUpdate?: (currentTime: number) => void;
className?: string;
}
export interface AudioPlayerRef {
seekTo: (time: number) => void;
play: () => void;
pause: () => void;
}
const PLAYBACK_SPEEDS = [0.75, 1, 1.25, 1.5, 2];
function formatTime(seconds: number): string {
if (!isFinite(seconds) || isNaN(seconds)) return '0:00';
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs.toString().padStart(2, '0')}`;
}
export const AudioPlayer = forwardRef<AudioPlayerRef, AudioPlayerProps>(
function AudioPlayer({ conversationId, audioFiles, onTimeUpdate, className }, ref) {
const audioRef = useRef<HTMLAudioElement>(null);
const [isPlaying, setIsPlaying] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [isMuted, setIsMuted] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);
const [playbackSpeed, setPlaybackSpeed] = useState(1);
const [showSpeedMenu, setShowSpeedMenu] = useState(false);
const [audioUrl, setAudioUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
// Load audio URL on mount
useEffect(() => {
let cancelled = false;
async function loadAudioUrl() {
if (!audioFiles || audioFiles.length === 0) {
setError('No audio files available');
setIsLoading(false);
return;
}
try {
setIsLoading(true);
setError(null);
const firstFile = audioFiles[0];
// Use signed URL if available (direct GCS access, no proxy needed)
// This avoids timeout issues with large audio files
if (firstFile.signed_url) {
setAudioUrl(firstFile.signed_url);
setIsLoading(false);
return;
}
if (firstFile.status === 'unavailable') {
setError('Audio is no longer available for this conversation');
setIsLoading(false);
return;
}
// The backend builds playback artifacts asynchronously; poll until
// the file is cached instead of streaming through the merge proxy
// that used to time out on long conversations.
const fileId = firstFile.id || '0';
const deadline = Date.now() + 90_000;
while (Date.now() < deadline && !cancelled) {
const { files, pollAfterMs } =
await getConversationAudioUrlsWithPoll(conversationId);
if (cancelled) return;
const info = files.find((f) => f.id === fileId) ?? files[0];
if (info?.signed_url) {
setAudioUrl(info.signed_url);
setIsLoading(false);
return;
}
if (info?.status === 'unavailable') {
setError('Audio is no longer available for this conversation');
setIsLoading(false);
return;
}
await new Promise((resolve) => setTimeout(resolve, pollAfterMs ?? 3000));
}
if (!cancelled) {
setError('Audio is still processing — try again shortly');
setIsLoading(false);
}
} catch (err) {
console.error('Failed to load audio:', err);
setError('Failed to load audio');
setIsLoading(false);
}
}
loadAudioUrl();
return () => {
cancelled = true;
};
}, [conversationId, audioFiles]);
// Expose methods via ref
useImperativeHandle(ref, () => ({
seekTo: (time: number) => {
if (audioRef.current) {
audioRef.current.currentTime = time;
setCurrentTime(time);
}
},
play: () => {
audioRef.current?.play();
},
pause: () => {
audioRef.current?.pause();
},
}));
const handlePlayPause = useCallback(() => {
if (!audioRef.current) return;
if (isPlaying) {
audioRef.current.pause();
} else {
audioRef.current.play();
}
}, [isPlaying]);
const handleTimeUpdate = useCallback(() => {
if (!audioRef.current) return;
const time = audioRef.current.currentTime;
setCurrentTime(time);
onTimeUpdate?.(time);
}, [onTimeUpdate]);
const handleLoadedMetadata = useCallback(() => {
if (!audioRef.current) return;
setDuration(audioRef.current.duration);
setIsLoading(false);
}, []);
const handleSeek = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
if (!audioRef.current) return;
const time = parseFloat(e.target.value);
audioRef.current.currentTime = time;
setCurrentTime(time);
}, []);
const handleSpeedChange = useCallback((speed: number) => {
if (audioRef.current) {
audioRef.current.playbackRate = speed;
}
setPlaybackSpeed(speed);
setShowSpeedMenu(false);
}, []);
const toggleMute = useCallback(() => {
if (audioRef.current) {
audioRef.current.muted = !isMuted;
}
setIsMuted(!isMuted);
}, [isMuted]);
const handleDownload = useCallback(() => {
if (!audioUrl) return;
// Open the signed URL directly - browser will handle the download
// This avoids CORS issues with fetching the blob
window.open(audioUrl, '_blank');
}, [audioUrl]);
const handleError = useCallback(() => {
setError('Failed to load audio');
setIsLoading(false);
}, []);
if (!audioFiles || audioFiles.length === 0) {
return null;
}
if (error) {
return (
<div
className={cn(
'flex items-center gap-3 p-3 rounded-xl bg-bg-tertiary border border-bg-quaternary/50',
'text-text-tertiary text-sm',
className,
)}
>
<VolumeX className="w-5 h-5" />
<span>{error}</span>
</div>
);
}
return (
<div
className={cn(
'flex items-center gap-3 p-3 rounded-xl bg-bg-tertiary border border-bg-quaternary/50',
className,
)}
>
{/* Hidden audio element */}
{audioUrl && (
<audio
ref={audioRef}
src={audioUrl}
onTimeUpdate={handleTimeUpdate}
onLoadedMetadata={handleLoadedMetadata}
onPlay={() => setIsPlaying(true)}
onPause={() => setIsPlaying(false)}
onError={handleError}
onEnded={() => setIsPlaying(false)}
preload="metadata"
/>
)}
{/* Play/Pause button */}
<button
onClick={handlePlayPause}
disabled={isLoading}
className={cn(
'w-10 h-10 rounded-full flex items-center justify-center',
'bg-purple-primary text-white',
'hover:bg-purple-secondary transition-colors',
'disabled:opacity-50 disabled:cursor-not-allowed',
'flex-shrink-0',
)}
>
{isLoading ? (
<Loader2 className="w-5 h-5 animate-spin" />
) : isPlaying ? (
<Pause className="w-5 h-5" />
) : (
<Play className="w-5 h-5 ml-0.5" />
)}
</button>
{/* Progress bar */}
<div className="flex-1 flex items-center gap-3">
<span className="text-xs text-text-tertiary w-10 text-right flex-shrink-0">
{formatTime(currentTime)}
</span>
<input
type="range"
min={0}
max={duration || 100}
value={currentTime}
onChange={handleSeek}
disabled={isLoading}
className={cn(
'flex-1 h-1.5 rounded-full appearance-none cursor-pointer',
'bg-bg-quaternary',
'[&::-webkit-slider-thumb]:appearance-none',
'[&::-webkit-slider-thumb]:w-3',
'[&::-webkit-slider-thumb]:h-3',
'[&::-webkit-slider-thumb]:rounded-full',
'[&::-webkit-slider-thumb]:bg-purple-primary',
'[&::-webkit-slider-thumb]:cursor-pointer',
'[&::-moz-range-thumb]:w-3',
'[&::-moz-range-thumb]:h-3',
'[&::-moz-range-thumb]:rounded-full',
'[&::-moz-range-thumb]:bg-purple-primary',
'[&::-moz-range-thumb]:border-0',
'[&::-moz-range-thumb]:cursor-pointer',
'disabled:opacity-50',
)}
style={{
background:
duration > 0
? `linear-gradient(to right, var(--purple-primary) ${(currentTime / duration) * 100}%, var(--bg-quaternary) ${(currentTime / duration) * 100}%)`
: undefined,
}}
/>
<span className="text-xs text-text-tertiary w-10 flex-shrink-0">
{formatTime(duration)}
</span>
</div>
{/* Playback speed */}
<div className="relative">
<button
onClick={() => setShowSpeedMenu(!showSpeedMenu)}
className={cn(
'px-2 py-1 rounded-md text-xs font-medium',
'bg-bg-quaternary text-text-secondary',
'hover:bg-bg-tertiary hover:text-text-primary transition-colors',
)}
>
{playbackSpeed}x
</button>
{showSpeedMenu && (
<div className="absolute bottom-full right-0 mb-2 py-1 bg-bg-secondary border border-bg-tertiary rounded-lg shadow-lg z-10">
{PLAYBACK_SPEEDS.map((speed) => (
<button
key={speed}
onClick={() => handleSpeedChange(speed)}
className={cn(
'w-full px-4 py-1.5 text-xs text-left',
'hover:bg-bg-tertiary transition-colors',
speed === playbackSpeed
? 'text-purple-primary font-medium'
: 'text-text-secondary',
)}
>
{speed}x
</button>
))}
</div>
)}
</div>
{/* Mute button */}
<button
onClick={toggleMute}
className={cn(
'p-2 rounded-md',
'text-text-secondary hover:text-text-primary transition-colors',
)}
>
{isMuted ? <VolumeX className="w-4 h-4" /> : <Volume2 className="w-4 h-4" />}
</button>
{/* Download button */}
<button
onClick={handleDownload}
disabled={!audioUrl}
className={cn(
'p-2 rounded-md',
'text-text-secondary hover:text-text-primary transition-colors',
'disabled:opacity-50 disabled:cursor-not-allowed',
)}
title="Download audio"
>
<Download className="w-4 h-4" />
</button>
</div>
);
},
);