To use the component in React, you must install react and @lit/react. Import the AmLyrics component from @uimaxbai/am-lyrics/react.
Important: You must include the 'use client'; directive at the top of your file if using Next.js App Router.
To sync with an audio element, use requestAnimationFrame or the timeupdate event to update the currentTime prop (in milliseconds).
'use client'; // VERY IMPORTANT!!!
import React, { useState, useCallback, useRef, useEffect } from 'react';
import { AmLyrics } from '@uimaxbai/am-lyrics/react';
export default function App() {
const [currentTime, setCurrentTime] = useState(0);
const audioRef = useRef<HTMLAudioElement>(null);
// Sync audio player time with the component
useEffect(() => {
const audio = audioRef.current;
if (!audio) return;
let animationFrameId: number;
const updateCurrentTime = () => {
setCurrentTime(audio.currentTime * 1000);
animationFrameId = requestAnimationFrame(updateCurrentTime);
};
const handlePlay = () => {
animationFrameId = requestAnimationFrame(updateCurrentTime);
};
const handlePause = () => {
cancelAnimationFrame(animationFrameId);
};
const handleTimeUpdate = () => {
setCurrentTime(audio.currentTime * 1000);
};
audio.addEventListener('play', handlePlay);
audio.addEventListener('pause', handlePause);
audio.addEventListener('timeupdate', handleTimeUpdate);
return () => {
cancelAnimationFrame(animationFrameId);
audio.removeEventListener('play', handlePlay);
audio.removeEventListener('pause', handlePause);
audio.removeEventListener('timeupdate', handleTimeUpdate);
};
}, []);
const handleLineClick = useCallback((event: Event) => {
const customEvent = event as CustomEvent<{ timestamp: number }>;
const audio = audioRef.current;
if (audio) {
audio.currentTime = customEvent.detail.timestamp / 1000;
audio.play();
}
}, []);
return (
<div>
<audio ref={audioRef} src="/uptown_funk.flac" controls />
<AmLyrics
songTitle="Uptown Funk"
songArtist="Mark Ronson"
query="Uptown Funk Mark Ronson"
currentTime={currentTime}
onLineClick={handleLineClick}
autoScroll
highlightColor='#fff'
/>
</div>
);
}