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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With