'Song overlapping the previous one

Playing.js

import { useEffect, useState, useMemo } from "react";

function Playing(props) {
  const [pauseToggle, setpauseToggle] = useState(false);
  const [song, setSong] = useState('CKay - Love Nwantiti');
  const [src, setSrc] = useState(require(`./Resources/Songs/${song}.mp3`));

  useEffect(()=>{
    if(props.currentSong.song == undefined){
      console.log('Undefined');
    }else{
      player();
      setSong(props.currentSong.song.song);
      setSrc(require(`./Resources/Songs/${song}.mp3`));
    }
  },[props, song, src]);

  const music = useMemo(() => new Audio(src), [src]);

  const player = () => {
    setpauseToggle(!pauseToggle);
    if (pauseToggle) {
      music.pause();
    } else {
      music.play();
    }
  }


  return (
    <div className="app">
      <div className="section3">
        <audio></audio>
        <i
          onClick={player}
          className={pauseToggle ? "fas fa-pause" : "fas fa-play pe-1"}>
        </i>
      </div>
    </div>
  );
}

export default Playing;

AllSong.js

const All_Song=[
 {
    song: 'Balti - Ya Lili feat. Hamouda',
    title: 'Thisiz Balti',
    image: 1,
    isPlaying: false,
    isFavourite: false,
  },{
    song: 'CKay - Love Nwantiti',
    title: 'Tik Tok Remix',
    image: 2,
    isPlaying: false,
    isFavourite: false,
  },{
    song: 'Goosebumps',
    title: 'HouseMusicHD',
    image: 3,
    isPlaying: false,
    isFavourite: false,
  },
];

{All_Song.map(song=>{
    return(
      <Link 
        key={song.image}
        to={{
          pathname:"/",
          state:{songInfo: song}
        }}
        onClick={() => props.setCurrentSong({song})}
      >
        <div>{song.song}</div>
      </Link>
    );
  })}

Suppose I play any song in the initial state and after going to the list of allsong and clicking on the next song starts playing that song in the background but it overlaps the previous song and simultaniously plays both the song without pausing the previous song. I basically have only basic knowledge about hooks so I just followed some tutorial regarding the useMemo hook.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source