I'm trying to have a song play in the background of my app when it loads. However, it's not working with useEffect. I've also tried using useState in the useEffect with the same results. In the code below, if I click on the Play
button, it works fine. Do you have any pointers on what I'm doing wrong?
First Attempt
const Footer = () => {
let audio = new Audio(onlyYou);
const start = () => {
audio.play();
};
const stop = () => {
audio.pause();
}
useEffect(() => {
start()
}, [])
return (
<footer>
<div>
<button onClick={start}>Play</button>
<button onClick={stop}>Stop</button>
</div>
</footer>
)
Second Attempt
const Footer = () => {
const [playSong, setPlaySong] = useState(false);
let audio = new Audio(onlyYou);
const start = () => {
audio.play();
};
const stop = () => {
audio.pause();
}
useEffect(() => {
setPlaySong(true)
}, [])
return (
<footer>
{playSong && start()}
<div>
<button onClick={start}>Play</button>
<button onClick={stop}>Stop</button>
</div>
</footer>
)