How to Play Audio in JavaScript

OpenJavaScript 0

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:

<button id="play">Play</button>

<script>

const pauseBtn = document.getElementById('pause');

const audio = new Audio();

audio.src = './happy.mp3';

playBtn.addEventListener('click', () => {
    audio.play(); // Avoids non-interaction error because triggered by a click
});

</script>

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

<button id="play">Play</button>
<button id="pause">Pause</button>

<script>

const playBtn = document.getElementById('play');
const pauseBtn = document.getElementById('pause');

const audio = new Audio();

audio.src = './happy.mp3';

playBtn.addEventListener('click', () => {
    audio.play();
});

pauseBtn.addEventListener('click', () => {
    audio.pause();
});

</script>

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

<select id="tracks">
    <option value="./happy.mp3">Happy</option>
    <option value="./ambient-piano.mp3">Ambient</option>
</select>

<script>

const trackSelect = document.getElementById('tracks');

trackSelect.addEventListener('change', (e) => {
    audio.src = e.target.value;
    audio.play();
});

</script>

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
<div>
    <p id="current-src">-</p>
    <p id="current-time">-</p>
    <p id="duration">-</p>
</div>

<button id="play">Play</button>
<button id="pause">Pause</button>

<button id="prev">Prev</button>
<button id="next">Next</button>

<select id="tracks">
    <option value="./happy.mp3">Happy</option>
    <option value="./ambient-piano.mp3">Ambient</option>
</select>

<script>

const playBtn = document.getElementById('play');
const pauseBtn = document.getElementById('pause');
const prevBtn = document.getElementById('prev');
const nextBtn = document.getElementById('next');
const trackSelect = document.getElementById('tracks');
const currentSrc = document.getElementById('current-src');
const currentTime = document.getElementById('current-time');
const duration = document.getElementById('duration');

let playlist = [];
let playIndex = 0;

for (option of trackSelect.children) {
    playlist.push(option.value); // Add all <option> urls to playlist array
}

const audio = new Audio();
audio.src = playlist[playIndex]; // Sets src to first url in playlist

// Respond to user-control events:
playBtn.addEventListener('click', () => {
    audio.play();
});

pauseBtn.addEventListener('click', () => {
    audio.pause();
});

prevBtn.addEventListener('click', () => {
    prevTrack();
});

nextBtn.addEventListener('click', () => {
    nextTrack();
});

trackSelect.addEventListener('change', (e) => {
    audio.src = e.target.value;
    audio.play();
});

// Respond to Audio object events:
audio.onended = () => {
    nextTrack();
};

audio.onloadedmetadata = () => {
    currentSrc.textContent = audio.currentSrc;
    duration.textContent = audio.duration;
};

audio.ontimeupdate = () => {
    currentTime.textContent = audio.currentTime;
};

// Define functions for next and previous track navigation:
function nextTrack() {
    if (playIndex !== playlist.length-1) {
        playIndex++;
    } else {
        playIndex = 0;
    }
    audio.src = playlist[playIndex];
    audio.play();
};

function prevTrack() {
    if (playIndex !== 0) {
        playIndex--;
    } else {
        playIndex = playlist.length-1;
    }
    audio.src = playlist[playIndex];
    audio.play();
};

</script>
Tags: