Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to toggle pause/play audio with button click in Pure Javascript?

I find in Stackoverflow before but almost example working in element.

Have any method toggle click play/pause when using Javascript?

HTML Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<button id="music" class="play-song"></button>

My JS code look like:

<script>
const elem = document.getElementById("music");
if (elem) {
elem.addEventListener ("click", playMusic, false);
}

function playMusic() {
  var musik= new Audio("/songs/1.mp3");
  musik.play();
  var current = this;
  if (current != elem) {
    elem.classList.remove('mute-audio');
  } else if (current.classList.contains('mute-audio') === true) {
    current.classList.remove('mute-audio');
  } else {
    current.classList.add('mute-audio');
  }
}
</script>

>Solution :

const elem = document.getElementById("music");
if (elem) {
elem.addEventListener ("click", playMusic, false);
}

var musik= new Audio("https://xomkey.com/wp-content/uploads/songs/xomkey-song.mp3");

function playMusic() {  
  if(musik.paused){
    musik.play();
    // do your other task
  } else {
    musik.pause();
    // do your other task
  }
  
}
<button id="music" class="play-song">Play/Pause</button>

You can play and pause with this piece of code like toggle. For audio, there are many more interesting methods.

For your reference:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement

https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading