HTML5 and CSS3 All-in-One For Dummies
Book image
Explore Book Buy On Amazon

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.

image0.jpg

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

<!doctype html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>audio.html</title>
</head>
<body>
 <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>
 </audio>
 <p>
 Music: J.S. Bach "Allemande" Partita for Violin #2
 </p>
</body>
</html>

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.

About This Article

This article is from the book:

About the book author:

Andy Harris taught himself programming because it was fun. Today he teaches computer science, game development, and web programming at the university level; is a technology consultant for the state of Indiana; has helped people with disabilities to form their own web development companies; and works with families who wish to teach computing at home.

This article can be found in the category: