Play / Pause audio file using JavaScript / jquery, select .attr

When playback is clicked, the mp3 file should be played by pressing MP3 again to pause playback. The goal is to get the file name from the "key" and add the + .mp3 directory to javascript / jquery after.

A game, but not a pause.

<span class="play" key="cef83b993c716dd543b6fa4f053cc4a4">Play</span>
<script>
  $(".play").click(function(){
    var audio = new Audio("beats/" + $(this).attr('key') + ".mp3");
    if (audio.paused) {
      audio.play();
    }   
    else {
      audio.pause();
    }
    $( this ).toggleClass( "pause" ); // switch to some new css for a pause button
  });
</script>
+4
source share
1 answer

The reason is that every time you click on it, it does the following:

var audio = new Audio("beats/" + $(this).attr('key') + ".mp3");

So what you need to do is add a condition in front:

var audio;
if (typeof audio == "undefined")
  audio = new Audio("beats/" + $(this).attr('key') + ".mp3");

Your complete code will be:

<span class="play" key="cef83b993c716dd543b6fa4f053cc4a4">Play</span>
<script>
  var audio;
  $(".play").click(function(){
    if (typeof audio == "undefined")
      audio = new Audio("beats/" + $(this).attr('key') + ".mp3");
    if (audio.paused) {
      audio.play();
    }   
    else {
      audio.pause();
    }
    $( this ).toggleClass( "pause" ); // switch to some new css for a pause button
  });
</script>
+7
source

Source: https://habr.com/ru/post/1608199/


All Articles