Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an audio play/pause button?

I recently learned about embedding audio in html like below.

 <audio controls>
  <source src="sample.ogg" type="audio/ogg">
  <source src="sample.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio> 

Which displays something like a rectangle with various options on it like pause/play, download, set volume etc.

But how can I instead of this "audio playing rectangle" have a button that when clicked plays the audio once and on clicking on it while the audio is playing pauses it and on clicking again continuous playing.

like image 935
Asif Ali Avatar asked Oct 22 '25 14:10

Asif Ali


1 Answers

You can use Javascript to perform such actions.

Try the following

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;
};

Just replace the parameters to yours.

like image 75
user6875529 Avatar answered Oct 24 '25 03:10

user6875529



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!