import type { NFTError } from '@/api/types'; import { useNFTContext } from '@/nft/components/NFTProvider'; import { type MouseEvent, useCallback, useEffect, useRef, useState, } from 'react'; import { cn } from '../../../styles/theme'; type NFTAudioProps = { className?: string; onLoading?: (mediaUrl: string) => void; onLoaded?: () => void; onError?: (error: NFTError) => void; }; export function NFTAudio({ className, onLoading, onLoaded, onError, }: NFTAudioProps) { const { animationUrl } = useNFTContext(); const audioRef = useRef(null); const [isPlaying, setIsPlaying] = useState(false); useEffect(() => { function onEnded() { setIsPlaying(false); } if (animationUrl && audioRef?.current) { audioRef.current.onloadstart = () => { onLoading?.(animationUrl); }; audioRef.current.onloadeddata = () => { onLoaded?.(); }; audioRef.current.addEventListener('ended', onEnded); audioRef.current.onerror = (error: string | Event) => { onError?.({ error: typeof error === 'string' ? error : error.type, code: 'NmNAc01', // NFT module NFTAudio component 01 error message: 'Error loading audio', }); }; } }, [animationUrl, onLoading, onLoaded, onError]); const handlePlayPause = useCallback( (event: MouseEvent) => { event.stopPropagation(); if (isPlaying) { audioRef.current?.pause(); setIsPlaying(false); } else { audioRef.current?.play(); setIsPlaying(true); } }, [isPlaying], ); if (!animationUrl) { return null; } return (
); }