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" );
});
</script>
source
share