This music player component includes the following features:
- Play/Pause toggle
- Skip to next and previous tracks
- Progress bar with current time and duration display
- Song information display (title and artist)
Here's a breakdown of the component:
- We use the
useStatehook to manage the player's state (playing status, current song, current time, and duration). - The
useRefhook is used to reference the HTML5 audio element. - The
useEffecthook is used to play or pause the audio when theisPlayingstate orcurrentSongchanges. - We have functions to toggle play/pause, skip to the next or previous song, and handle time updates.
- The progress bar is implemented using the
Slidercomponent from shadcn/ui, allowing users to seek through the song. - We format the time display using a helper function
formatTime.
To use this component, you would need to replace the mock songs array with your actual song data, including valid audio file paths.
Note that this is a client-side component, as indicated by the "use client" directive at the top. This is necessary because we're using browser APIs (audio playback) and React hooks that are not available in server components.
We can further enhance this music player by adding features like a playlist, volume control, or even integrating with a music streaming API for a more complete experience.