Q.1. I am trying to write a code in Joomla using a JCE Editor where I have a audio file which I am trying to play on the bowser. Following is the java script code I have written;
<script type="text/javascript">
var audio, playbtn;
function initAudioPlayer() {
audio = new Audio();
audio.src = "/images/audios/how-to-meditate/relaxation/relaxation-in-the-forest.mp3";
audio.loop = false;
audio.pause();
//set object references
playbtn = document.getElementById("playpausebtn");
//Add Event Handling
playbtn.addEventListener("click", playPause);
//Funtions
function playPause() {
if (audio.pause) {
audio.play();
playbtn.style.background = "url(images/icons/pause.JPG)";
} else {
audio.pause();
playbtn.style.background = "url(images/icons/play.JPG) no-repeat";
}
}
}
window.addEventListener("load", initAudioPlayer);
</script>
Following is the CSS code;
<style scoped="scoped" type="text/css">
button#playpausebtn {
background: url(images/icons/play.JPG) no-repeat;
border: none;
width: 40px;
height: 40px;
cursor: pointer;
outline: none;
}
And the button code for html;
<button id="playpausebtn"></button>
In this case while executing when I click the play button the audio plays but when I click the button second time to stop the audio it doesn't stop where as nothing happens and the audio continues to play although I have included the else statement which specifies if the audio.pause is not true i.e if audio is playing then on click the audio should stop and the play button should be displayed but none of it happens. I have tried inverting the code where write the below code;
function playPause() {
if (audio.play) {
audio.pause();
playbtn.style.background = "url(images/icons/play.JPG) no-repeat";
} else {
audio.play();
playbtn.style.background = "url(images/icons/pause.JPG)";
}
}
Then in this case only when the audio is playing and if I click on the pause button it works and when I try to play the audio it does not play.
So in both cases I observed that the code inside else does not execute and I couldn't understand why it is happening.
I am using Joomla 3.7.5 and the script is allowed in the JCE Editor
Kindly advise the reason for the problem.
Q.2. Also at last I want to know how to write a code to display play button once the audio is completely done playing?