play audio on button click html

Playing Audio on Button Click in HTML

If you want to add an audio file to your HTML page and play it on the click of a button, you can do it by using the audio tag and the onclick attribute.

Step 1: Add the Audio File

First, add the audio file to your HTML page using the audio tag. You can give it an ID or a class for easier identification:

<audio id="myAudio" src="audio-file.mp3"></audio>

Step 2: Add the Button

Next, add a button to your HTML page that will trigger the audio file to play. You can also give it an ID or a class:

<button id="myBtn">Play Audio</button>

Step 3: Add JavaScript Code

Finally, add JavaScript code to your HTML page that will play the audio file on the click of the button. You can use the onclick attribute to call a function that will play the audio:

<script>
  var audio = document.getElementById("myAudio");
  var btn = document.getElementById("myBtn");

  btn.onclick = function() {
    if (audio.paused) {
      audio.play();
      btn.innerHTML = "Pause Audio";
    } else {
      audio.pause();
      btn.innerHTML = "Play Audio";
    }
  };
</script>

This code creates two variables: one for the audio tag and one for the button tag. It then sets the onclick attribute of the button to a function that will play or pause the audio depending on its current state.

Multiple Ways to Do It

There are multiple ways to play audio on button click in HTML. One way is to use the audio tag and the onclick attribute, as described above. Another way is to use the Audio() constructor in JavaScript:

<script>
  var audio = new Audio("audio-file.mp3");
  var btn = document.getElementById("myBtn");

  btn.onclick = function() {
    if (audio.paused) {
      audio.play();
      btn.innerHTML = "Pause Audio";
    } else {
      audio.pause();
      btn.innerHTML = "Play Audio";
    }
  };
</script>

This code creates a new Audio() object with the audio file URL as its argument. It then sets the onclick attribute of the button to a function that will play or pause the audio in the same way as before.

You can also use third-party libraries like jQuery or AngularJS to add audio to your HTML page and play it on button click. However, the basic steps remain the same: add the audio file, add the button, and add JavaScript code to play or pause the audio on click.

That's it! Now you can add audio to your HTML page and play it on button click using different methods.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe