Search code examples
javascriptaudio

how to make play/pause button


I would like the pause button to resume the song from where it was paused instead of restarting the song.

with vanilla javascript only please, Thank you !

var songs = [
  "song1.mp3",
  "song2.mp3",
  "song3.mp3",
];

var song = new Audio();
var currentSong = 0;

var playButton = document.querySelector(".play");
var pauseButton = document.querySelector(".pause");

function playSong() {
  song.src = songs[currentSong];
  pauseButton.style.display = "block";
  playButton.style.display = "none";
  songTitle.textContent = sT[currentSong];
  Artist.textContent = artistNames[currentSong];
  songCover.src = songCovers[currentSong];
  song.play();
}

playButton.addEventListener("click", function playSong() {
  song.src = songs[currentSong];
  pauseButton.style.display = "block";
  playButton.style.display = "none";
  songTitle.textContent = sT[currentSong];
  Artist.textContent = artistNames[currentSong];
  songCover.src = songCovers[currentSong];
  song.play();
});

pauseButton.addEventListener("click", function pauseSong() {
  song.pause();
  pauseButton.style.display = "none";
  playButton.style.display = "block";
});


Solution

  • The song resets because every time you click on the play button, the src of the song is being assigned again. And therefor the song will start over from the start.

    So you'll need to change the part of your code where the song is selected. Do that outside of the play function so that clicking play will only play, and clicking pause will only pause.

    function chooseSong() {
      song.src = songs[currentSong];
      songTitle.textContent = sT[currentSong];
      Artist.textContent = artistNames[currentSong];
      songCover.src = songCovers[currentSong];
    }
    
    function playSong() {
      pauseButton.style.display = "block";
      playButton.style.display = "none";
      song.play();
    }
    
    function pauseSong() {
      pauseButton.style.display = "none";
      playButton.style.display = "block";
      song.pause();
    }
    
    playButton.addEventListener('click', playSong);
    pauseButton.addEventListener('click', pauseSong);
    
    chooseSong();