How to Stop and Play HTML Audio with JavaScript?

Estimated read time 1 min read

You can use the audio element in HTML and control it with JavaScript. Here’s an example that plays and stops an audio file:

<audio id="myAudio">
  <source src="your-audio-file.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

<button onclick="playAudio()">Play</button>
<button onclick="pauseAudio()">Pause</button>

<script>
  const audio = document.getElementById("myAudio");
  
  function playAudio() {
    audio.play();
  }
  
  function pauseAudio() {
    audio.pause();
  }
</script>

In the example above, two buttons trigger the playAudio() and pauseAudio() functions, respectively, to play and pause the audio file. The audio file is specified in the source element and can be in different formats like mp3, wav, ogg, etc.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply