Home > Blockchain >  How to stop current music if I click to play another music in javascript
How to stop current music if I click to play another music in javascript

Time:07-14

Please I need logic code that does if on click it will stop the current music before another music begins to play.

Here my js code:

$("body").delegate(".playFreeBeat", "click", function (e) 

//something similar like this:

   var audioplay = new Audio(); //Creating a object of Audio class
      var currentSong = 0;
      console.log(audioplay.duration);
      if (audioplay.duration > 0) {
        audioplay.pause();
      } else {
        audioplay.src = "./freeAudio/"   arraySong[0].songFiles; //set the source of 0th song

        audioplay.play(); // play the song
        
      
  
   }
});

CodePudding user response:

Basically you stop (pause) the old one before you play the new one.

I just built upon your code, but it could be improved.

var audioplay

$("body").delegate(".playFreeBeat", "click", function(e) {

  if (audioplay && audioplay.pause) {
    audioplay.pause();
  }
  audioplay = new Audio(); //Creating a object of Audio class
  var currentSong = 0;
  console.log(audioplay.duration);
  if (audioplay.duration > 0) {
    audioplay.pause();
  } else {
    audioplay.src = "./freeAudio/"   arraySong[0].songFiles; //set the source of 0th song

    audioplay.play(); // play the song

  }
});

CodePudding user response:


const elementExists = document.querySelector("audio");
if(elementExists)
while (elementExists[0]) elementExists[0].parentNode.removeChild(elementExists[0])
document.querySelector(‘body’).innerHTML  = "<audio src=‘SourceToAudioFile’/>"
document.querySelector("audio").play()
}else{
  document.querySelector(‘body’).innerHTML  = "<audio src=‘SourceToAudioFile’/>"
document.querySelector("audio").play()
}
  • Related