I believe I need to use the state to track which song is playing but I'm having trouble with implementing it. I'm not sure which param to pass in to react audio player or where to set the state. Is this possible? This is what the whole component looks like:
import { useState, useEffect } from 'react';
import ReactAudioPlayer from 'react-audio-player';
import { useSelector, useDispatch } from 'react-redux';
import { NavLink, useParams } from 'react-router-dom';
import { deleteSong, getOneSong } from '../../store/song';
import EditSongForm from '../EditSongForm';
const SpecificSong = ({ id, songName, songLink, userId, albumImage }) => {
const [editShowForm, setEditShowForm] = useState(false);
// const [currentlyPlayingSong, setCurrentlyPlayingSong] = useState(false)
const dispatch = useDispatch();
useEffect(() => {
dispatch(getOneSong(id));
setEditShowForm(false);
}, [dispatch, id]);
const editFormCheck = (e) => {
if (editShowForm) setEditShowForm(false)
if (!editShowForm) setEditShowForm(true)
}
const remove = (e) => {
dispatch(deleteSong(e.target.id));
}
const user = useSelector((state) => state.session.user);
const CurrentUserId = user?.id
return (
<div className='songdetails' key={id}>
<NavLink to={`/song/${id}`}>
<p className='songname' key={id}>{songName}</p>
<img className="albumimage" src={albumImage} alt="album image" srcset="" />
<ReactAudioPlayer
className='audioplayer'
src={songLink}
controls
key={songLink}
/>
</NavLink>
{userId === CurrentUserId ?
<>
<div className='editbutton'>
<EditSongForm props={id} />
</div>
<div className='removebutton'>
<button id={id} onClick={remove}>Delete Song</button>
</div>
</>
: null}
</div>
);
};
export default SpecificSong;
I couldn't recreate your issue exactly. But I think I can help.
According to my tests, this library handles the playing and pausing for individual components by itself so you don't need to touch that.
Now, to implement a locking mechanism you can store a Audio Player Index that tracks the index/key of the audio player that is playing now. If no player is playing the value defaults to a number such as "-1". So, whenever you play a react-audio-player component you first check whether another audio player is ON at the moment. If it is ON, turn that OFF and put your own key index on the variable AudioPlayerIndex. This variable might be stored in the Context API or Global Store as it will needed by all the audio player components inside your App.
From the API that was seen on their GitHub repo, linked here: https://github.com/justinmc/react-audio-player#readme