HTML5 introduces built-in media support via the <audio>
element, which offers you the ability to easily and quickly embed your audio media into HTML documents.
The main advantage of the <audio>
element is that it provides support for playing audio media without requiring external plug-ins.
Until now, there has not been a standard for playing audio files on web pages. What you commonly find on websites is that audio files are played through external plug-ins such as flash or other third party audio components. HTML5 defines this new element which now provides a standard way to embed audio within a web document.
Internet Explorer 9, Firefox, Opera, Chrome, and Safari support the <audio>
element. However, Internet Explorer 8 and previous versions, do not support the <audio>
element and would require a fall back mechanism to play audio on a web page.
Audio Format and Browser Support
Browser | MP3 | Wav | Ogg |
---|---|---|---|
Apple Safari 5+ | Yes | Yes | No |
Firefox 4+ | No | Yes | Yes |
Google Chrome 6+ | Yes | Yes | Yes |
Internet Explorer 9+ | Yes | No | No |
Opera 10.6+ | No | Yes | Yes |
Example
The <audio>
element contains child elements so that the source files and fallback options can be configured. Multiple source files can be specified using the <source>
element in order to provide the audio encoded in different formats for different browsers. The controls
attribute adds audio controls, such as play, pause, and volume.
<audio controls>
<source src="audio.mp3" type="audio/mp3">
<source src="audio.ogg" type="audio/ogg">
Audio playback is not supported by your browser.
</audio>
DOM Methods, Properties and Events
HTML5 has DOM methods, properties, and events for the <audio>
element. These methods, properties, and events allow you to manipulate <audio>
element using JavaScript. You can use methods for playing, pausing, and loading the videos. There are also DOM events that can notify you when the audio begins to play, is paused, and/or has ended, for example.
<!DOCTYPE html>
<html>
<body>
<div style="text-align:center">
<button onclick="playPause()">Play/Pause</button>
<br/><br/>
<audio id="audio1" >
<source src="audio.mp3" type="audio/mp3">
<source src="audio.ogg" type="audio/ogg">
Audio playback is not supported by your browser.
</audio>
</div>
<script>
var myAudio=document.getElementById("audio1");
function playPause() {
if (myAudio.paused)
myAudio.play();
else
myAudio.pause();
}
</script>
</body>
</html>