HTML5 > Multimedia

Audio in HTML5

How to play audio in web page using HTML5?

To know the events details of multimedia elements of HTML5, read this. In this post, we shall learn how to handle audio media in web page using HTML5.

To play audio in HTML5, we can use the <audio> tag which is introduced in HTML5. At the time of writing this post, any one of .mp3, .wav or .ogg audio files are supported in all new browsers like Google Chrome, FireFox etc. Below are html5 audio player code.

    <audio src="/DemoSupportingFiles/Multimedia/TechFundaAudio.mp3" controls>
    audio is not supported.    

In the above code snippet the .mp3 auido file is placed in <audio> tag that will be played.


HTML5 audio tag attributes

Following are different attributes

  • autoplay – boolean - allows automatically play the audio when page loads
  • controls – display audiocontrols like play, pause, volume etc.
  • height – height of the audiodisplay area
  • loop – loop the playing of audiowhen it finished playing
  • muted - boolean - if true, the audio of the audiowill be muted
  • preload - can have following values
    • none - the audioshould not be preloaded
    • metadata - only the meta data (the length of the video) should be fetched from the server
    • auto - (is by default) decided by the browser, in this case the whole audiofile can be downloaded by the browser
  • src - the url of the audioto play
  • width – width of the audioplay area

In case we want to display a feedback text on the page when audio is not supported, we can write the message in between <video> tag.

HTML5 audio with multiple media source files

To ensure the audio is playing in all different browsers, we can specify multiple media source files using <source> tag. Below is the sample code snippet.

<audio controls autoplay>
        <source src="/DemoSupportingFiles/Multimedia/TechFundaAudio.mp3" type="audio/mp3">
        <source src="/DemoSupportingFiles/Multimedia/TechFundaAudio.ogg" type="audio/ogg">
        <p>Audio is not supported.</p>

To know what different types of audio media are supported and what are different html5 audio events in HTML5 at the time of writing this post, click here.

 Views: 6503 | Post Order: 102

Write for us

Hosting Recommendations