Search code examples
javascripthtml5-audio

How do i get the javascript .pause() function to work?


Hello i am working on adding some music to my website and the .play() function works as intended but the .pause() does not it is getting called but just does not work for some reason thanks for ur help

`

 var audio = new Audio(songs[song_number].link); //link of the current audio
  if (isPlaying == true) {
    audio.currentTime = 0;
    audio.pause();
    document.getElementById("playButton"+song_number).src = "./extern_media/playbutton.png" //Switches image
    document.getElementById("playButton"+song_number).width = "80"; //Changes Width
    isPlaying = false;
  }
  else{
    isPlaying = true;
    console.log(song_number);
    console.log(songs[song_number].link);
    audio.play();
    document.getElementById("playButton"+song_number).src = "./extern_media/pausebutton.png"
    document.getElementById("playButton"+song_number).width = "50";}

`

I am expecting the audio in the background to pause when i hit the button a second time. THe imgae switch works and so does the .play() function but the .pause() just doesnt work.


Solution

  • You are creating a new Audio element each time

    You have to use the same element