Button "Play/Pause" - How to restart playback?

Asked

Viewed 550 times

1

I made a simple button "play/pause" for audio, with the following script:

<audio id="myAudio"         
src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>

<script type="text/javascript" charset="utf-8" async defer>
var myAudio = document.getElementById("myAudio");
var isPlaying = false;

function togglePlay() {
if (isPlaying) {
myAudio.pause()
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
</script>    

However, I would actually like to click the button "play/pause" instead of pausing, restart from '0' playback. Some light?

1 answer

1


Add myAudio.currentTime = 0; to the function myAudio.onpause:

var myAudio = document.getElementById("myAudio");
var isPlaying = false;

function togglePlay() {
   if (isPlaying) {
      myAudio.pause()
   } else {
     myAudio.play();
   }
};

myAudio.onplaying = function() {
   isPlaying = true;
};
myAudio.onpause = function() {
   myAudio.currentTime = 0;
   isPlaying = false;
};
<audio id="myAudio" preload="auto" controls>
   <source src="http://www.sousound.com/music/healing/healing_01.mp3" type="audio/mpeg">
</audio>

  • Thank you, successfully implemented!

  • @dib Valeu!!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.