Computers & ProgrammingHTML/XHTMLWeb Development

How to Play Audio in HTML

Adding audio can be just as challenging as adding video to your HTML web pages. Fortunately, with a little help, adding audio content to your HTML pages can be easy.

There are several methods of adding audio and each method has its own advantages and disadvantages. There are many different methods that can be used to add media to your pages.

Please note that some of the methods listed below are not supported in HTML 4.01. You either have to have a browser that supports HTML5 or your users will have to install the required plug-ins.

Here are the most common ways to add a video to your web pages.

Audio Element

The <audio> element is an HTML5 element. Within the <audio> element, you can add multiple <source> elements so that the browser can choose which file is best to download.

Here is an example:

<audio controls="controls">
    <source src="musicFile.mp3" type="audio/mpeg"/>
    <source src="musicFile.ogg" type="audio/ogg"/>
    Text content in the event that no audio can be played.
</audio>

Embed & Object Elements

You can also use the <embed> and/or <object> elements to try to play multimedia elements in HTML pages. While the <object> element is supported in HTML4, the <embed> element is not.

If the browser does not support the file format, the audio will not play. Using this method is not easy when supporting various types of browsers.

Here is an example of how to play audio using both elements:

<embed src="musicFile.mp3" height="50" width="250"/>
<object data="musicFile.mp3" height="50" width="250"/>

Use Multiple Solutions

Another method is to use various elements so that at least one method is likely to be supported by the user’s browser. Keep in mind that this option includes HTML4 and HTML5 elements. For your page to validate correctly, you will need to use the HTML5 DOCTYPE, <!DOCTYPE HTML>.

In this example, the browser will attempt to play the audio using one of the elements in this order: audio, object, then embed. Here is an example.

<audio controls="controls">
    <source src="musicFile.mp3" type="audio/mpeg" />
    <source src="musicFile.ogg" type="audio/ogg" />
    <object data="musicFile.mp3" height="50" width="250">
        <embed src="musicFile.mp3" height="50" width="250">
            Text content in the event that no audio can be played.
        </embed>
    </object>
</audio>

Again, my suggestion is to implement an audio solution that is easy to maintain while still providing a meeting of the needs of your users.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top