I am creating an audio player in React and I have the following code. It plays fine when you click on the play button once but refuses to pause when you click pause. Also if you click play again, instead of just continuing the audio it creates new audio of the same song and plays it on top of the previous song. I'm not sure how to fix this.
const AudioPlayer = () => {
let audio = new Audio(song)
const [playing, setPlaying] = useState(false)
const playHandler = () => {
if(playing){
setPlaying(false)
console.log(playing)
}
else{
setPlaying(true)
}
}
const audioPause = () => {
audio.pause()
}
const audioPlay = () => {
audio.play()
}
useEffect (() => {
(playing) ? audioPlay() : audioPause()
}, [playing])
return(
<div className="songPlaying">
<p> { (playing) ? "Now playing" : "Stopped Playing" } </p>
<button type="submit" onClick={playHandler}>
{(playing) ? "Pause" : "Play" }
</button>
</div>
)
}