Computers & ProgrammingHTML5Web Development

HTML5 Audio

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

BrowserMP3WavOgg
Apple Safari 5+YesYesNo
Firefox 4+NoYesYes
Google Chrome 6+YesYesYes
Internet Explorer 9+YesNoNo
Opera 10.6+NoYesYes

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>

Leave a Comment

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

Scroll to Top