How to Add Audio to Your HTML5 and CSS3 Based Web Pages - dummies

How to Add Audio to Your HTML5 and CSS3 Based Web Pages

By Andy Harris

HTML has supported images for a long time, but now it works just as well with audio files. This is a major breakthrough, as audio previously required external programs like Flash.


It’s quite easy to add audio to a web page in HTML5 with the new <audio> tag. Here’s the code for creating this page:

<!doctype html>
<html lang="en">
 <meta charset="UTF-8">
 <h1>Audio Demo</h1>
 <audio controls = "controls">
 <source src = "Allemande.mp3" type = "audio/mpeg">
 <source src = "Allemande.ogg" type = "audio/ogg">
  Your browser does not support HTML5 Audio
  Please use this link instead:
  <a href = "Allemande.mp3">Allemande.mp3</a>
 Music: J.S. Bach "Allemande" Partita for Violin #2

Although nearly every current browser supports the tag, they still can’t agree on which format to support. Some browsers support MP3 files, some support a newer standard called Ogg, and some support WAV.

The best way to be sure the sound plays is to supply two different formats. Often, including both Ogg and MP3 formats ensures that audio will play on all major browsers.

To add an audio file to your page, follow these steps:

  1. Add the audio tag to your page.

    The tag indicates where an audio file will be placed. Where you place the tag in the code corresponds to where the controls will appear.

  2. Turn on controls.

    You can specify a control panel with the attribute. This causes a small control to appear. If you leave this directive out, there will be no control panel, which means the user will not be able to play the clip.

  3. Create aelement or two.

    Inside the pair, add one or more elements. Each source element indicates a file you will link to.

  4. Set thesrcattribute to indicate the file.

    The attribute of the tag is used to indicate the file name of the audio file you wish to play.

  5. Add alternate code for older browsers.

    Any additional HTML code between the and tags will be interpreted only by browsers that do not understand the sound tag. You can add an ordinary anchor to download the sound effect if you wish. This way, even those with older browsers can hear what they’re missing.