Everything You Should Know About the Audio Tag in HTML and JavaScript

Include audio in HTML, and play and pause it in JavaScript

Javascript Jeep🚙💨
May 26 · 4 min read
Image for post
Image for post
Audio cheat sheet

The audio tag allows you to add audio to your web pages. The audio tag is introduced in HTML5 .

Adding an audio tag is super easy:

<audio src="/music/meow.mp3"> </audio>

You can also show a message if the browser doesn’t support the audio tag:

<audio src="/music/meow.mp3">    You're browser is Outdated . Please Update The Browser</audio>

Attributes

Controls

The above code alone doesn’t play the music or show anything. We need to add the controls attribute to enable play and pause of the audio. By default, controls is false. You can add enable control of the audio tag by adding either controls or controls = "true”.

<audio src="/music/meow.mp3" controls>    You're browser is Outdated . Please Update The Browser</audio>

Don’t forget to add controls; otherwise, nothing will be displayed.

Multiple audio sources

If you’re having multiple source files for the same audio track, then you need to use the source tag to include multiple audio tracks. If you have mp3, ogg, wav, use the following:

<audio controls>  <source src="meow.ogg" type="audio/ogg" />
<source src="meow.mp3" type="audio/mpeg" />
<source src="meow.wav" type="audio/wav" />
Your browser does not support the audio tag.</audio>

From the above code, Browser tries to play the meow.ogg.

  • If the browser can play meow.ogg, the browser doesn’t load other files.
  • If meow.ogg is not supported, then the browser will load the audio from next source.

autoplay

You can set theautoplay attribute to play audio automatically once the audio is loaded.

<audio autoplay></audio><!-- Second Way -->
<audio autoplay="true"></audio>

Note: Mobile browsers don’t allow autoplay.

If you don’t set autoplay, then the browser won’t load the audio. The audio metadata (e.g., duration, name) will be downloaded, but the browser will not download the audio itself. You can also force downloading of the audio by setting thepreload attribute as auto.

<audio preload="auto"></audio>

Different preload values:

  • none → The audio should not be preloaded.
  • metadata → Only audio metadata (e.g., length) is fetched.
  • auto → The whole audio file can be downloaded, even if the user is not expected to use it.
  • empty string → Alias for auto

muted

If you set themuted attribute, then the audio sound will be muted.

<audio muted></audio><!-- Second Way -->
<audio muted="true"></audio>

loop

You can enable the audio to play in a loop (i.e., the audio will play continuously from the beginning after it has played completely) by setting the loop attribute.

<audio loop></audio><!-- Second Way -->
<audio loop="true"></audio>

Note: Audio is subject to CORS, and unless you allow it on the server, an audio file can’t be played cross-origin.

Use Audio in JavaScript

Getting the audio element first.

let audio = document.getElementById('audio');

Check audio state

Check whether the audio is paused by using thepaused attribute. If the audio is playing, then paused is false, otherwise true.

let isPaused = audio.paused;let isPlaying = !isPaused;

Control audio

To pause the audio, you can use pause method.

audio.pause();

To play the paused audio, you can use play method.

audio.play();

Browser volume

You can change the browser volume using the following.

audio.volume = 1; // 100 %audio.volume = 0.5; // 50%

Current time

You can get the current playback time of audio using thecurrentTime attribute. currentTime returns a double-precision, floating-point value indicating the current playback position, in seconds, of the audio.

audio.currentTime;

Rewind

To rewind the track, you can use the following.

myAudio.currentTime = 0; 
myAudio.play();

Fast forward

To fast forward 30 seconds, use this:

myAudio.currentTime = 30; 
myAudio.play();

Duration

To get the duration of the audio, you can use duration attribute.

audio.duration

When getting duration:

  • If no media is present on the element, or the media is not valid, the returned value is NaN.
  • If the media has no known end (such as for livestreams of unknown duration, web radio, media incoming from WebRTC, and so forth), this value is +Infinity.

Important Audio Events

play → triggered once the audio starts playing

audio.addEventListener('play', function(ev){console.log("audio started playing");});

pause → triggered once the audio is paused

audio.addEventListener('pause', function(ev){console.log("audio paused. Do you want to change track");});

ended → triggered once the audio playing is completed

audio.addEventListener('ended', function(ev){console.log("audio Ended"); 
// ask user about re-playing the same song & other operations
});

timeupdate → The user interacted with the playback timeline and went forward/backward.

audio.addEventListener('timeupdate', function(ev){console.log("Current time", this.currentTime);});

volumechange → The user changed the volume.

audio.addEventListener('volumechange', function(ev){let currentVolume = this.volume;if(currentVolume > .75) {
alert("Over Sound may damage your ears");
}
});

waiting → Playback has stopped because of a temporary lack of data.

audio.addEventListener('waiting', function(ev) => {
console.log('Audio is waiting for more data.');
});

Read about more events here.

Better Programming

Advice for programmers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store