Open In App

JavaScript- Play a .mp3 File in JS

Last Updated : 19 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To play a .mp3 file in JavaScript, you can use the HTML <audio> element along with JavaScript to control playback. These are the following ways to do that:

1. Basic HTML and JavaScript Approach (Mostly Used)

The <audio> tag is used to embed sound files, and its src attribute points to the .mp3 file you want to play. The JS the audio player and play button using getElementById. When the button is clicked, the audioPlayer.play() method is called, which starts playing the audio.

HTML
<!DOCTYPE html>
<html lang="en">
<body>
 <button id="playButton">Play Audio</button>
 <audio id="audioPlayer" src=
"https://media.geeksforgeeks.org/wp-content/uploads/20240912183739/chatbot-response.mp3"></audio>

 <script>
  const audioPlayer = document.getElementById('audioPlayer');
  const playButton = document.getElementById('playButton');
  playButton.addEventListener('click', () => {
   audioPlayer.play();
  });
 </script>
</body>
</html>

2. With Play/Pause Toggle

The button text changes dynamically to reflect whether the audio is playing or paused. audioPlayer.paused checks whether the audio is currently paused. If it is, the audio is played, and if it's playing, the audio is paused.

HTML
<!DOCTYPE html>
<html lang="en">
<body>
 <button id="playPauseButton">Play Audio</button>
 <audio id="audioPlayer" src=
"https://media.geeksforgeeks.org/wp-content/uploads/20240912183739/chatbot-response.mp3"></audio>
 <script>
  const audioPlayer = document.getElementById('audioPlayer');
  const playPauseButton = document.getElementById('playPauseButton');

  playPauseButton.addEventListener('click', () => {
   if (audioPlayer.paused) {
    audioPlayer.play();  
    playPauseButton.textContent = 'Pause Audio';  
   } else {
    audioPlayer.pause();  
    playPauseButton.textContent = 'Play Audio';  
   }
  });
 </script>
</body>
</html>

Next Article
Article Tags :

Similar Reads