How to toggle pause/play audio with button click in pure javascript?

Member

by deron , in category: Javascript , a year ago

How to toggle pause/play audio with button click in pure javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , a year ago

@deron 

You can toggle the pause/play functionality of an audio element using JavaScript by following these steps:

  1. Create an HTML audio element in your HTML file:
1
<audio id="myAudio" src="path/to/audio.mp3"></audio>


  1. Add a button in your HTML file to trigger the pause/play functionality:
1
<button id="playPauseButton">Play/Pause</button>


  1. Add JavaScript code to toggle the pause/play functionality when the button is clicked:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// Get the audio element and the play/pause button
const myAudio = document.getElementById("myAudio");
const playPauseButton = document.getElementById("playPauseButton");

// Add a click event listener to the button
playPauseButton.addEventListener("click", function() {
  // Check if the audio is currently paused
  if (myAudio.paused) {
    // If paused, play the audio
    myAudio.play();
    playPauseButton.textContent = "Pause"; // Update button text to "Pause"
  } else {
    // If playing, pause the audio
    myAudio.pause();
    playPauseButton.textContent = "Play"; // Update button text to "Play"
  }
});


Now, when the button is clicked, it will either pause or play the audio, and the button text will update accordingly.