I have developed a function that plays and pauses music. It is designed to be simple and lightweight for small audio samples, with basic play and stop functionalities. The issue I'm encountering is that after playing the music for the second time, the classes are not switching correctly for pausing.
Below is the jQuery code snippet:
var isPlaying = false;
function playMusic(){
var audioElement = document.createElement('audio');
var audioElementSrc = $(this).attr('data-audio-src');
if (isPlaying != true)
{
isPlaying = true;
audioElement.setAttribute('src', audioElementSrc);
$.get();
audioElement.addEventListener("loadeddata", function(){
audioElement.play();
}, true);
audioElement.addEventListener("ended", function() {
isPlaying = false;
});
$(this).addClass('pause');
$(this).removeClass('play');
$('.pause').click(function() {
audioElement.pause();
isPlaying = false
$(this).removeClass('pause');
$(this).addClass('play');
});
}
else
{
return false;
}
}
$(function(e){
$('.play').click(playMusic);
});
You can view the jsfiddle Here which showcases the issue - when you click on stop and then try to play again, the classes do not switch as expected.