Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play / Pause audio file with JavaScript / jquery by fetching .attr

When play is pressed the file mp3 should play when clicked again the mp3 should pause. The goal is to fetch the file name from 'key' and add the directory + .mp3 in javascript / jquery after.

Its playing but not pausing.

<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>
like image 403
Jeff Avatar asked Mar 15 '23 17:03

Jeff


1 Answers

The reason is, everytime you click on it, it executes this:

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

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

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

Your full code would 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>
like image 107
Praveen Kumar Purushothaman Avatar answered Mar 17 '23 05:03

Praveen Kumar Purushothaman