I’m trying to make a React Music Player but I don’t know why, the volume is not updating in real time. The volume only changes whenever I stop the audio and then play it again.
const [volume, setVolume] = useState(1)
const [isPlaying, setIsPlaying] = useState(false);
const audioRef = React.createRef();
const togglePlay = () => {
const audio = audioRef.current;
if (!audio) return;
audio.volume = volume;
if (isPlaying) {
audio.volume = 0;
} else {
audio.volume = Number(volume);
audio.play();
console.log(volume)
}
setIsPlaying((prevIsPlaying) => !prevIsPlaying);
};
The input:
<input type="range" value={volume} onChange={(e) => setVolume(parseFloat(e.target.value))} max="1" min="0"/>
I’ve tried to use Chat-GPT to help me fix this error
2
Answers
I would use the useEffect React hook, in order to keep the state data consistent with the (HTML) Audio object.
So every time either
volume
orisPlaying
variable is changed, the hook is then executed, and by comparing the values of the actual Audio object and your state, you would depending on the variable changed; either call the Audio API or change the Audio refs value.PS: Remember, autoplay is usually blocked by browsers. https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
How about to use useEffect hook?
Like this :