A podcast, an interview, a song, the ambient sound of a place… Audio also has its own native element in HTML5: audio. If you followed the previous lesson, it will feel very familiar, because it shares most of its attributes with video, as well as its way of offering several formats. But sound poses its own challenges: it's more intrusive than an image (you can't "not look" at it), browsers heavily restrict autoplay and, for deaf people, all its content is lost if there is no transcript. In this lesson you will learn how to insert audio with controls, offer several formats, configure its playback sensibly and make it accessible. With it, The Blue Cup will have ambient sound in the gallery and an interview with its head baker in the news, and you will complete the module on links and media.
Contents
- The
audioelement - Attributes:
controls,autoplay,loop,mutedandpreload autoplayand browser policies- Several formats with
source - Fallback content
- Accessibility: transcripts
- Good practice: sound, always with permission
- Project: ambience and an interview at The Blue Cup
The audio element
The minimal way to insert audio is:
src: path of the sound file, in the project'smedia/folder.controls: shows the browser's player (play/pause, progress bar, time, volume).
Important differences from video:
- Without
controls, audio is completely invisible: it takes up no space on the page and the user has no way of playing or stopping it. Unless you control it with JavaScript (beyond the scope of this course),controlsis essential. - It has no
width,heightorposter: there's no image to show. The width of the player depends on the browser and will be adjusted with CSS. - It doesn't support subtitles with
trackin any useful way: the text alternative for audio is a transcript on the page itself (you will see this later).
Like video, it has a closing tag and can contain source elements and fallback content.
Attributes: controls, autoplay, loop, muted and preload
| Attribute | Type | Effect | Example use |
|---|---|---|---|
controls |
Boolean | Shows the player | Practically always |
autoplay |
Boolean | Tries to play when the page loads | Almost never (see the next section) |
loop |
Boolean | Starts again when it finishes | Ambient sound, background music |
muted |
Boolean | Starts muted | Rare for audio: muted audio makes no sense unless the user turns it on |
preload |
none / metadata / auto |
How much to download in advance | none or metadata in most cases |
Remember the Boolean attribute trap: loop="false" turns on looping. To turn it off, remove it.
preload works exactly as in Embedding Videos:
none: downloads nothing until "play" is pressed. Ideal for long podcast episodes or pages with several audio files.metadata: downloads only the duration and the basic data; that way the player can show "3:45" from the start.auto: may download the whole file; keep it for when the audio is the page's main content.
autoplay and browser policies
Modern browsers block autoplay of sound except in specific circumstances. The exact rules vary between browsers, but in general:
| Situation | Does it play by itself? |
|---|---|
Audio with autoplay when the page is opened for the first time |
No: it's blocked |
Audio with autoplay and muted |
Yes, but silently (useless for audio) |
| After the user has interacted with the page (a click, a key press) | Usually, yes |
| Sites the user visits often and where they usually play content | Sometimes, depending on the browser |
In other words: even if you write autoplay, you can't count on it playing. And even if it did, it would be a bad idea, as you will see in the good practice section. If you want to check this, open the DevTools console: when the browser blocks autoplay, it usually leaves a warning.
Several formats with source
Just as with video, you can offer the audio in several formats so that each browser chooses the first one it can play:
<audio controls preload="none">
<source src="media/ambience.ogg" type="audio/ogg">
<source src="media/ambience.mp3" type="audio/mpeg">
</audio>- The browser goes through the
sourceelements in order and uses the first compatible one. - Thanks to
type, it knows this without downloading the file. - The MIME type for MP3 is
audio/mpeg, notaudio/mp3: a very common mistake.
Audio formats for the web:
| Format | Extension | MIME type (type) |
Compression | Compatibility | Notes |
|---|---|---|---|---|---|
| MP3 | .mp3 |
audio/mpeg |
Lossy | Universal | The safe option; if you only offer one, make it this one |
| AAC | .m4a, .aac |
audio/mp4 / audio/aac |
Lossy | Universal in modern browsers | Slightly better quality than MP3 at the same size |
| Ogg Vorbis | .ogg |
audio/ogg |
Lossy | All except some older versions of Safari | Open format |
| Opus | .opus, .webm |
audio/ogg; codecs=opus, audio/webm |
Lossy | Modern browsers | Excellent for speech at very small file sizes |
| WAV | .wav |
audio/wav |
Uncompressed | Wide | Huge files: don't use it on the web |
File size tips: for speech (an interview, a podcast), around 64 kbps in mono is enough; for music, between 128 and 192 kbps in stereo. A minute of speech at 64 kbps takes up less than 0.5 MB; the same minute in WAV, around 10 MB.
Fallback content
As with video, whatever you write inside audio (apart from the source elements) is only shown in browsers that don't understand the element. Offer a link to the file:
<audio controls preload="none">
<source src="media/ambience.ogg" type="audio/ogg">
<source src="media/ambience.mp3" type="audio/mpeg">
<p>Your browser can't play audio. <a href="media/ambience.mp3">Download the ambient sound (MP3, 1.2 MB)</a>.</p>
</audio>Remember that fallback content isn't shown if the browser understands audio but fails to load the file, and that it doesn't replace a transcript.
Accessibility: transcripts
A deaf person can't access the content of an audio file. Nor can someone in a library without headphones, or someone who would rather skim-read than listen for twenty minutes. The solution is a transcript: the full text of what is said, published on the page itself.
A good transcript:
- Captures everything that is said, indicating who is speaking.
- Includes relevant sounds in square brackets:
[laughs],[the door bell rings]. - Is close to the audio, or linked from it with clear text.
- Is ordinary HTML: headings, paragraphs,
strongfor the speaker's name… Which also means search engines can index it.
<h3>Transcript</h3>
<p><strong>Interviewer:</strong> What time does your day start?</p>
<p><strong>Carmen:</strong> I'm already in the bakery by five. [laughs] Bread doesn't wait.</p>For purely ambient audio, with no words, a brief description in the accompanying text is enough: "Ambient sound from the café: conversations, the coffee machine and cups".
Later on you will be able to show a long transcript collapsed, so that it doesn't take up the whole page, with the
detailselement, which you will see in Other Semantic Elements: time, address, details and dialog (Module 6).
Good practice: sound, always with permission
Unexpected sound is one of the most annoying experiences on the web:
- It startles and embarrasses people: nobody wants their laptop to start making noise in a meeting or in a library.
- It interferes with screen readers: a blind person navigates by listening to their screen reader; if the page plays music, they can't hear their own tool. The accessibility guidelines (WCAG) require any automatic sound lasting more than 3 seconds to be able to be paused or muted independently.
- It uses up data without the user asking for it.
That's why the golden rules are:
- Never play sound automatically. The user should press "play".
- Always show the controls (
controls), so that the audio can be paused, the volume adjusted or playback stopped. - Explain what the audio is before the player: what it contains and how long it lasts.
- Offer a transcript of the spoken content.
- Only use
loopfor ambient sounds, and never combined withautoplay.
Project: ambience and an interview at The Blue Cup
The audio files
| File | Content |
|---|---|
media/ambience.mp3 |
Ambient sound from the café (1 minute, looped) |
media/ambience.ogg |
The same sound in Ogg (optional) |
media/baker-interview.mp3 |
Fictional interview with Carmen, the head baker (around 2 minutes, speech at 64 kbps) |
You can record them yourself on your mobile or use any freely licensed test audio.
- Ambient sound in
gallery.html
gallery.htmlAt the end of the gallery, after the video, add:
<h2>The sound of The Blue Cup</h2>
<p>Close your eyes and listen to a morning in the café: conversations, the hiss of the coffee machine and the clinking of cups (1 minute, loops).</p>
<audio controls loop preload="none">
<source src="media/ambience.ogg" type="audio/ogg">
<source src="media/ambience.mp3" type="audio/mpeg">
<p>Your browser can't play audio. <a href="media/ambience.mp3">Download the ambient sound (MP3, 1.2 MB)</a>.</p>
</audio>- No
autoplay: visitors decide whether they want to listen. loop: it's an ambient sound, so it makes sense for it to repeat, and since there arecontrols, it can be stopped at any time.preload="none": the gallery already has images and video; the audio isn't downloaded until it's requested.- The preceding paragraph describes the content and its duration, and warns that it loops. Since it's a sound with no words, that description serves as its text alternative.
- An interview with a transcript in
news.html
news.htmlIn the bread-making workshop news item, after the paragraph with the head baker's quotation, add:
<h3>Listen to the interview with Carmen, our head baker</h3>
<p>We chatted with Carmen about sourdough and what you will learn on the workshop (2 minutes).</p>
<audio controls preload="metadata">
<source src="media/baker-interview.mp3" type="audio/mpeg">
<p>Your browser can't play audio. <a href="media/baker-interview.mp3">Download the interview (MP3, 1 MB)</a>.</p>
</audio>
<h4>Interview transcript</h4>
<p><strong>Interviewer:</strong> Carmen, what time does your day start in the bakery?</p>
<p><strong>Carmen:</strong> At five in the morning. [laughs] When we open at eight, the bread has to be cooling already.</p>
<p><strong>Interviewer:</strong> What's so special about sourdough?</p>
<p><strong>Carmen:</strong> It's a living ferment. You have to feed it every day and give it time. That's why I always say sourdough won't be rushed.</p>
<p><strong>Interviewer:</strong> What will people take home from the workshop?</p>
<p><strong>Carmen:</strong> Their own sourdough starter, in a jar, and a loaf they've baked themselves. [the oven timer goes off] And that's mine! See you on the first Saturday of the month.</p>preload="metadata": this way the player shows the duration from the start, without downloading the whole file.- Only MP3 is offered: it's a universal format and, for speech, it's enough. You don't always have to provide several formats.
- The transcript goes straight after the audio, with a lower-level heading (
h4, because it sits under the interview'sh3, which in turn sits under the news item'sh2): the heading hierarchy is still correct, as you learnt in Headings and Paragraphs. - Each contribution is a paragraph with the speaker's name in
strong, and includes relevant sounds in square brackets.
Project status at the end of the module
Go through the whole site with Live Server. This is what The Blue Cup has now:
| Page | What's new in Module 3 |
|---|---|
| All | Logo linked to the home page and a common menu of six links |
index.html |
Link to the menu, clickable bookings card, anchors to #opening-hours and menu.html#coffees, tel: phone number and mailto: email, external links to the reviews and the guide |
menu.html |
Internal index of anchors, "Back to top" and a downloadable PDF menu |
gallery.html |
Storefront, decorative divider, product photos, video with a poster image and subtitles, ambient sound |
news.html |
Link to the supplier, link to bookings, audio interview with a transcript |
contact.html |
Address, clickable phone number and email, link to the opening hours |
bookings.html |
Skeleton with a heading and the menu (the form will arrive in Module 5) |
Common Mistakes and Tips
- Forgetting
controls: the audio is invisible and the user can't play or stop it. - Relying on
autoplay: browsers block it and, even if it worked, it would be annoying and harm accessibility. type="audio/mp3": the correct type for MP3 isaudio/mpeg.loop="false"to turn off looping: it turns it on. Remove the attribute.- Publishing WAV files or studio-quality MP3s for speech: they are far larger than necessary.
- Not describing the audio before the player: users don't know what they are going to hear or how long it lasts.
- Forgetting the transcript for interviews and podcasts.
- Tip: before adding sound to a page, ask yourself whether it adds anything. If the answer is "atmosphere", offer it, but let the visitor be the one who decides to press "play".
Exercises
Exercise 1. Write the code for a podcast episode media/podcast-ep01.mp3 (25 minutes, 12 MB) that is also available as media/podcast-ep01.ogg. It must show the controls, download nothing until the user asks for it, offer fallback content and have a heading and a description before it.
Exercise 2. Find and correct the errors:
<audio autoplay loop>
<source src="media/music.mp3" type="audio/mp3">
<source src="media/music.wav" type="audio/wav">
</audio>Exercise 3. The Blue Cup wants its home page to play a welcome tune automatically on a loop "to create atmosphere". In three or four points, explain why it isn't a good idea and suggest an HTML alternative.
Solutions
Solution 1.
<h2>"Coffee and Sourdough" podcast, episode 1</h2>
<p>In this first episode we talk about how we choose our seasonal coffee (25 minutes).</p>
<audio controls preload="none">
<source src="media/podcast-ep01.ogg" type="audio/ogg">
<source src="media/podcast-ep01.mp3" type="audio/mpeg">
<p>Your browser can't play audio. <a href="media/podcast-ep01.mp3">Download episode 1 (MP3, 12 MB)</a>.</p>
</audio>
<p><a href="news.html#ep01-transcript">Read the transcript of episode 1</a></p>preload="none" avoids downloading 12 MB for people who aren't going to listen. The link to the transcript is a recommended extra (it would point to a section with that id).
Solution 2.
<p>Music we play in the café (3 minutes).</p>
<audio controls loop preload="none">
<source src="media/music.ogg" type="audio/ogg">
<source src="media/music.mp3" type="audio/mpeg">
<p><a href="media/music.mp3">Download the music (MP3, 3 MB)</a>.</p>
</audio>- Without
controls, the audio was invisible and impossible to stop: it's added. autoplayis removed: it would be blocked and, besides, it's bad practice.- The type for MP3 is
audio/mpeg, notaudio/mp3. - WAV isn't suitable for the web because of its size: it's replaced with Ogg (or you could keep only the MP3).
- A preceding description,
preloadand fallback content are added.
Solution 3.
- Browsers block autoplay with sound: it probably wouldn't even play.
- If it did play, it would surprise and annoy visitors (at work, on public transport) and make them leave the page.
- It would interfere with blind people's screen readers, who would no longer be able to hear their navigation tool.
- It would use up mobile data without permission.
Alternative: a visible, optional player, like the one in the gallery:
<p>Want to feel as if you were at The Blue Cup? Listen to our ambient sound (1 minute, loops).</p>
<audio controls loop preload="none">
<source src="media/ambience.mp3" type="audio/mpeg">
</audio>Conclusion
With the audio element you complete the Links and Media in HTML module. You know how to insert sound with controls, offer several formats with source and the correct type (audio/mpeg for MP3, audio/ogg, AAC), choose how much to preload with preload, use loop sensibly, understand why browsers block autoplay and, above all, respect your visitors: sound only plays when they ask for it, and all spoken content comes with its transcript. Over the course of the module, The Blue Cup has gone from a set of isolated text pages to a navigable, multimedia site: a common menu and logo, anchors, a clickable phone number and email address, a downloadable menu, images with good alt text, a subtitled video, ambient sound and a transcribed interview. But if you look at menu.html again, you will see that the prices are still written as "Product: €2.40" inside lists: impossible to compare in columns and harder to read the longer the menu gets. That data is crying out for a table. In the next module, Tables in HTML, you will start with the lesson Basic Table Structure and turn the price list into a proper table.
HTML Course
Module 1: Introduction to HTML
- What Is HTML?
- Setting Up Your Work Environment
- Basic Structure of an HTML Document
- Tags, Elements and Attributes
- Creating Your First HTML Page
- File Organisation and Paths
Module 2: Text Formatting in HTML
- Headings and Paragraphs
- Text Formatting Tags
- Lists: Ordered, Unordered and Description Lists
- Block Quotes and Preformatted Text
- Block and Inline Elements: div and span
Module 3: Links and Media in HTML
- Creating Hyperlinks
- Special Links: Anchors, Email, Phone and Downloads
- Adding Images
- Embedding Videos
- Using the Audio Element
Module 4: Tables in HTML
- Basic Table Structure
- Table Head, Body and Foot
- Merging Cells: colspan and rowspan
- Accessible Tables: caption, scope and headers
- Styling Tables
Module 5: Forms in HTML
- Creating a Basic Form
- Form Elements: input, textarea and select
- HTML5 Input Types
- Labels and Grouping: label, fieldset, legend and datalist
- Form Attributes and Validation
- Submitting Forms
Module 6: HTML5 Semantic Elements
- Introduction to Semantic HTML
- header, nav and footer
- article, section and aside
- main and figure
- Other Semantic Elements: time, address, details and dialog
Module 7: Advanced HTML Techniques
- HTML Entities
- Using iframes
- Data Attributes
- Metadata: meta, SEO and Open Graph
- Microdata and Structured Data
- Graphics in HTML: SVG and canvas
Module 8: Integrating HTML and CSS
- Linking CSS to HTML
- Inline, Internal and External CSS
- Basic CSS Selectors
- The Box Model
- Styling HTML Elements
- Introduction to Layout with Flexbox and Grid
Module 9: Responsive Web Design
Module 10: Best Practices and Accessibility
- HTML Best Practices
- Validating HTML Code
- Web Accessibility Basics
- Using ARIA Roles and Attributes
- Accessibility Testing
- Performance and Resource Loading
