Inserting audio into a webpage used to be challenging because web browsers lacked a unified standard for embedding media files like audio.
This section illustrates various methods for embedding sound in your webpage, ranging from a simple link to the use of the latest HTML5 <audio>
element.
The HTML5 <audio>
element, a recent addition, offers a standardized way to embed audio in web pages. While relatively new, it functions across most modern web browsers.
The following example demonstrates inserting audio into an HTML5 document using the browser's default controls, with a single source specified by the src
attribute.
<audio controls="controls" src="media/birds.mp3">
Your browser does not support the HTML5 Audio element.
</audio>
An audio is inserted with default browser controls, along with alternative sources.
<audio controls="controls">
<source src="media/birds.mp3" type="audio/mpeg">
<source src="media/birds.ogg" type="audio/ogg">
Your browser does not support the HTML5 Audio element.
</audio>
In the above example, the 'ogg' track functions in Firefox, Opera, and Chrome, while the 'mp3' track ensures compatibility with Internet Explorer and Safari.
Linking to audio files allows users to play them by clicking on the links.
Explore the following example to grasp this concept:
<a href="media/sea.mp3">Track 1</a>
<a href="media/wind.mp3">Track 2</a>
The <object>
element serves to embed various media files into an HTML document. Initially designed for ActiveX controls, it now accommodates any media object such as audio, video, PDF files, Flash animations, or even images.
The following example embeds a basic audio file into a webpage.
<object data="media/sea.mp3"></object>
<object data="media/sea.ogg"></object>
Warning: The <object>
element lacks broad support and its compatibility depends on the embedded object type. Alternative methods like the HTML5 <audio>
element or third-party HTML5 audio players may be more suitable in many cases.
The <embed>
element enables the embedding of multimedia content into an HTML document.
The following code snippet demonstrates embedding audio files into a webpage.
<embed src="media/wind.mp3">
<embed src="media/wind.ogg">
Warning: Although the <embed>
element enjoys wide browser support and is a standard part of HTML5, your audio may not play due to lack of browser support for that file format or unavailable plugins.