HTML Music Codes

This page demonstrates how to add music to a website using HTML code. It also outlines various options available to you so that you can ensure your users area able to hear your audio.

HTML5 <audio> Element

You can add HTML music code to your website by using the HTML5 <audio> tag.

This element was only first introduced in HTML5 which at the time of writing, was still under development, so be sure to check your music code in different browsers. While most (if not all) major browsers support the actual <audio> element, there is varying support for different file formats.

Fallback content (i.e. the content between the <audio> and </audio> tags) is displayed by user agents that don't support this element.

HTML <embed> Element

Before the <audio> element was introduced to HTML, many webmasters added music codes to their website by using the <embed> tag.

Even though this element has been around for a long time, it wasn't actually part of the HTML specification until HTML5.

Example

You can embed a music file into your page using the following HTML code:

This code will present a music console with the appropriate controls. If you don't see any music controls and don't hear any music, you may need to download a plugin for your browser.

Nesting <embed> Inside <audio>

So, for maximum browser compatibility, you can nest the <embed> element inside the <audio> tag, and it would look something like this (the same as our code above):

Be sure to test the <embed> element in various browsers, as you may get some unexpected results.

Need to create a music playlist?

You can make your music player loop through more than one song using a music playlist.

How to preload a sound file

You can preload music files so that the music file is loaded in the background before the user clicks on the "Play" button. You can preload using the following technique:

On the <audio> tag, you can add the preload attribute. Possible values are none, metadata, and auto. By specifying auto, the audio/music should start downloading in the background as soon as the page has loaded. By specifying metadata, it will only download related metadata, such as the first keyframe, duration, size etc.

Example:

You can also preload when using the <embed> tag. To do this, use the following code:

This embeds the sound, but the 'autostart' feature is off (you don't want to annoy the user now, do you?) and the 'hidden' feature is true, so the user doesn't see a console upon entering your webpage.

How to link to a music file

You can also link to a music file using the <a> tag. All you need to do is write something like this:

This assumes that the music file is in the specified location.