Last updated: December 15, 2023.

You can play an audio file in JavasScript by creating an Audio object, setting a URL and then calling the play() method on it:

const audio = new Audio(); // Generates new Audio object, equivalent of HTML 

To prevent an error occurring when calling play() because the user has not interacted with the page, you can call it in response to a click event:



The audio can be paused using the pause() method:




To change track, set a new src value and call play():



Below are some useful events and properties available on an Audio object:

// Do something when current track ends:
audio.onended = () => {
    console.log("Track just finished playing");
};

// Constantly get time as track plays:
audio.ontimeupdate = () => {
    console.log(audio.currentTime);
};

// After new track has loaded, get duration and url:
audio.onloadedmetadata = () => {
    console.log(audio.duration);
    console.log(audio.currentSrc);
};

Below is an example that combines most of the above to create a JavaScript audio player with:

  • Track selection
  • Play controls (play, pause, previous and next track)
  • Display of current track information











Share.
Leave A Reply