Tutorials HTML Audio & Video
Ch 16 / 40
Chapter 16 Beginner 9 min read HTML

HTML Audio & Video Elements

Before HTML5, embedding audio or video in a webpage required third-party plugins like Flash — which were slow, insecure, and unsupported on mobile. HTML5 introduced the native <audio> and <video> elements, letting browsers play media directly. In this chapter you'll master both elements, all their attributes, format fallbacks with <source>, captioning with <track>, and media accessibility best practices.

What you'll learn
The <audio> element — all attributes and usage
The <video> element — poster, dimensions, accessibility
Multiple format fallbacks with <source>
Captions and subtitles with <track> and WebVTT
Supported audio and video formats — browser compatibility
Autoplay policies and media accessibility rules

The <audio> Element

The <audio> element embeds sound content directly in a web page. It renders the browser's native audio player when the controls attribute is present. Without controls, the audio is completely invisible — useful for background music controlled by JavaScript.

<audio src="lecture.mp3" controls preload="metadata" loop muted >
  Your browser does not support the audio element.
</audio>
src Path to the audio file — can be relative or absolute URL
controls Shows the browser's native play/pause/volume UI controls
preload Hints to the browser how much to load before play
loop Automatically restarts audio from the beginning when it ends
muted Starts audio silenced — required for autoplay in many browsers
Fallback text Shown only in very old browsers that don't support HTML5 audio
HTML — audio element examples
<!-- Basic audio player with controls -->
<audio src="lecture.mp3" controls>
  Your browser does not support the audio element.
</audio>

<!-- Multiple formats for browser compatibility -->
<audio controls preload="metadata">
  <source src="lecture.ogg" type="audio/ogg">
  <source src="lecture.mp3" type="audio/mpeg">
  Your browser does not support HTML5 audio.
</audio>

<!-- Background audio (JS-controlled, no UI) -->
<audio id="bg-music" src="ambient.mp3"
       loop muted preload="auto">
</audio>

The <video> Element

The <video> element embeds video content natively — no Flash, no plugins. It supports all the same attributes as <audio>, plus video-specific attributes like poster, width, and height. Here is a mock player showing what the element renders:

Live demo — <video> with controls rendered
▶
K2infocom — Web Dev Course Preview · 16:9 · MP4
▶
🔊
02:14 / 06:30
⛶
HTML — video element examples
<!-- Basic responsive video with controls -->
<video
  src="course-preview.mp4"
  controls
  poster="thumbnail.jpg"
  width="800"
  height="450"
  preload="metadata"
>
  Your browser does not support the video element.
</video>

<!-- Multiple formats + captions -->
<video controls poster="thumb.jpg" width="100%">
  <source src="video.webm" type="video/webm">
  <source src="video.mp4"  type="video/mp4">
  <track
    src="captions-en.vtt"
    kind="captions"
    srclang="en"
    label="English"
    default
  >
  Your browser does not support HTML5 video.
</video>

<!-- Autoplaying hero video (muted required) -->
<video
  src="hero-bg.mp4"
  autoplay
  muted
  loop
  playsinline
  preload="auto"
  aria-hidden="true"
></video>

All <audio> & <video> Attributes

Here is a complete reference of every attribute supported by the audio and video elements:

controls Player Controls Both
Boolean attribute. Shows the browser's built-in media controls — play/pause, volume, seek bar, fullscreen (video), download. Without it the media is invisible or plays silently. Always include for accessible media.
src Media Source Both
The URL of the media file. Can be relative (video.mp4) or absolute. Omit when using multiple <source> child elements for format fallbacks — the browser picks the first format it supports.
autoplay Auto Play Both
Boolean. Starts playback automatically without user interaction. Browsers block autoplay with sound by default. To autoplay, you must also set muted. Use sparingly — autoplaying media is disruptive and an accessibility failure for some users.
muted Muted Both
Boolean. Starts the media silenced — the user can unmute via controls. Required for autoplay to work in Chrome, Firefox, and Safari. Also used for decorative background videos that should not make sound.
loop Loop Both
Boolean. The media restarts from the beginning when it ends — plays continuously. Useful for ambient background video/audio and short animation loops. Use alongside muted for background videos.
preload Preload Hint Both
Hints how much the browser should download before the user plays. Values: none (load nothing until play), metadata (load duration, dimensions only), auto (load the full file). Default varies by browser. Use metadata for performance.
poster Poster Image Video only
URL of an image displayed as the video thumbnail before playback starts. If omitted, the browser shows the first frame (which may be black for a moment). Always set a poster for a professional look and to reduce layout shift.
width / height Dimensions Video only
Sets the intrinsic width and height of the video in pixels. Setting both prevents layout shift while the video loads. For responsive video, set width="100%" in CSS and use aspect-ratio: 16/9 instead of fixed pixel values.
The playsinline Attribute
On iOS (iPhone/iPad), videos default to opening in fullscreen when played. Adding playsinline to a <video> element makes it play inline within the page — essential for background hero videos and inline video players. Always include it alongside autoplay muted loop for background videos.

The <source> Element — Format Fallbacks

Different browsers support different media formats. The <source> element lets you provide multiple format options — the browser picks the first format it can play and ignores the rest. This ensures maximum compatibility without JavaScript.

HTML — source element for format fallback
<!-- Video fallback: WebM → MP4 -->
<video controls poster="thumb.jpg" width="800" height="450">
  <!-- Browser tries WebM first (smaller file size) -->
  <source src="video.webm" type="video/webm">
  <!-- Falls back to MP4 if WebM unsupported -->
  <source src="video.mp4"  type="video/mp4">
  <!-- Text shown only in non-HTML5 browsers -->
  <p>Your browser doesn't support HTML5 video.
     <a href="video.mp4">Download it</a>.</p>
</video>

<!-- Audio fallback: OGG → MP3 -->
<audio controls>
  <source src="audio.ogg" type="audio/ogg">
  <source src="audio.mp3" type="audio/mpeg">
  Your browser does not support HTML5 audio.
</audio>

Here is the browser support matrix for the most common media formats:

Format Type MIME type Chrome Firefox Safari Best Use
MP4 (H.264) Video video/mp4 ✓ ✓ ✓ Universal fallback — widest support
WebM (VP9) Video video/webm ✓ ✓ Partial Smaller file size — use first, fall back to MP4
OGG Theora Video video/ogg ✓ ✓ ✗ Open-source — not recommended as primary format
MP3 Audio audio/mpeg ✓ ✓ ✓ Universal audio — safe default for all browsers
OGG Vorbis Audio audio/ogg ✓ ✓ ✗ Open-source audio — use before MP3 as first source
WAV Audio audio/wav ✓ ✓ ✓ Uncompressed — large files, use for short sound effects only
Recommended Strategy
For video: provide WebM first (smaller, faster) then MP4 as fallback. For audio: provide OGG first then MP3 as fallback. The browser picks the first supported format and stops. Always include the type attribute on each <source> — without it the browser must download part of each file to detect the format.

The <track> Element — Captions & Subtitles

The <track> element adds timed text tracks to video (and audio) — captions, subtitles, chapter markers, and descriptions. It uses WebVTT (.vtt) files — a plain-text format for timed text. WCAG 1.2.2 requires captions for all pre-recorded video with audio.

kind="captions"
Captions include all audio information — dialogue, sound effects, music cues — for deaf or hard-of-hearing users. They are shown in the video's language. This is the most important track type for accessibility compliance (WCAG 1.2.2).
kind="subtitles"
Subtitles contain spoken dialogue translated into another language — for viewers who don't understand the video's spoken language. They typically do not include sound effect descriptions.
kind="descriptions"
Audio descriptions describe visual content for blind or low-vision users — what is shown on screen that audio alone doesn't convey. Read aloud by screen readers or text-to-speech.
kind="chapters"
Chapter markers let users jump to named sections of a long video — like a table of contents for the video. Browsers may display these as a chapter navigation UI.
HTML — track element with multiple languages
<video controls poster="thumb.jpg" width="800" height="450">
  <source src="course.mp4" type="video/mp4">

  <!-- English captions (default) -->
  <track
    src="captions-en.vtt"
    kind="captions"
    srclang="en"
    label="English"
    default
  >

  <!-- Hindi subtitles -->
  <track
    src="subtitles-hi.vtt"
    kind="subtitles"
    srclang="hi"
    label="हिंदी"
  >

  <!-- Gujarati subtitles -->
  <track
    src="subtitles-gu.vtt"
    kind="subtitles"
    srclang="gu"
    label="ગુજરાતી"
  >

  <!-- Chapter markers -->
  <track
    src="chapters.vtt"
    kind="chapters"
    srclang="en"
    label="Chapters"
  >
</video>

Here is what a WebVTT caption file (.vtt) looks like:

captions-en.vtt — WebVTT caption file format
WEBVTT 1 00:00:00.000 --> 00:00:03.500 Welcome to the HTML Tutorial at K2infocom. 2 00:00:04.000 --> 00:00:08.200 In this chapter, we'll cover all HTML5 media elements. 3 00:00:08.500 --> 00:00:13.000 Let's start with the <audio> element and its key attributes. 4 00:00:13.200 --> 00:00:18.500 [sound of keyboard typing] Then we'll explore the <video> element.
WebVTT Format Rules
Every WebVTT file starts with WEBVTT on the first line. Each cue has an optional number, a timestamp line (start --> end in HH:MM:SS.mmm format), and one or more lines of caption text. Blank lines separate cues. Sound effects and non-speech audio should be included in captions inside square brackets — e.g. [music playing].

Autoplay Policy — Why Autoplay Doesn't Always Work

All major browsers block autoplay with audio. This is an intentional policy to prevent unwanted noise. Here is exactly how it works and what you can do:

autoplay + muted ✅ Always works
A video with autoplay muted will always play automatically in all browsers. This is the recommended approach for hero background videos and introductory animations. The user can unmute with controls if you provide them.
autoplay (with sound) ❌ Blocked
Chrome, Firefox, and Safari all block autoplay with sound by default unless the user has interacted with the site before (has clicked, scrolled, etc.). Attempting autoplay with audio silently fails — the browser ignores the attribute with no error.
User interaction ✅ Then autoplay works
After the user has interacted with the page (click, tap, scroll), browsers allow JavaScript to call .play() with audio. Use a play button as the trigger — then call audio.play() on click.
HTML + JS — Safe autoplay pattern
<!-- ✅ Background video — always autoplays -->
<video
  src="hero-bg.mp4"
  autoplay muted loop playsinline
  aria-hidden="true"
></video>

<!-- ✅ Audio triggered by user click -->
<button type="button" id="playBtn">▶ Play Intro</button>
<audio id="intro-audio" src="intro.mp3" preload="auto"></audio>

<script>
  document.getElementById('playBtn')
    .addEventListener('click', () => {
      document.getElementById('intro-audio').play();
    });
</script>

Responsive & Accessible Video

Making video work perfectly on all screen sizes and for all users requires a few CSS and HTML patterns:

HTML + CSS — Responsive video with fixed aspect ratio
<!-- Responsive wrapper preserving 16:9 aspect ratio -->
<div class="video-wrap">
  <video
    controls
    poster="thumb.jpg"
    preload="metadata"
    aria-label="K2infocom HTML Tutorial — Chapter 16"
  >
    <source src="ch16.webm" type="video/webm">
    <source src="ch16.mp4"  type="video/mp4">
    <track src="ch16-en.vtt" kind="captions"
           srclang="en" label="English" default>
  </video>
</div>

/* CSS — responsive 16:9 video */
.video-wrap {
  width: 100%;
  aspect-ratio: 16 / 9;
  border-radius: 12px;
  overflow: hidden;
}
.video-wrap video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}
Decorative vs Informative Video
For decorative background videos (no spoken content, purely visual): add aria-hidden="true" to hide from screen readers. For informative videos with speech: add aria-label="Video description" and always provide a <track kind="captions"> for hearing-impaired users.

Common Mistakes — Do's & Don'ts

These are the most frequent audio/video mistakes beginners make:

Do — Correct
<!-- Provide multiple formats -->
<video controls poster="thumb.jpg">
  <source src="v.webm" type="video/webm">
  <source src="v.mp4"  type="video/mp4">
  <!-- Captions for accessibility -->
  <track src="caps.vtt"
         kind="captions"
         srclang="en"
         label="English"
         default>
</video>

<!-- Background: autoplay muted -->
<video autoplay muted loop
       playsinline
       aria-hidden="true">
</video>
Don't — Wrong
<!-- Single format only — breaks Firefox -->
<video src="video.ogv" controls>
</video>

<!-- No captions — WCAG 1.2.2 failure -->
<video controls>
  <source src="lecture.mp4"
           type="video/mp4">
</video>

<!-- Autoplay with audio — blocked -->
<video autoplay src="noisy.mp4">
<!-- Browser silently ignores -->
</video>

Try It Yourself

Edit the media page below and click Open in Editor to see audio and video elements rendered live in full screen with real controls.

Live Editor
✎ Editor
👁 Preview
Try This
The live editor loads real audio and video from W3Schools public samples — click play to test controls. Add autoplay muted loop to the <video> tag and see the video start automatically (muted). Remove muted — the browser will silently block autoplay with sound.
Free Resource
HTML5 Cheat Sheet — All Tags & Attributes
One printable PDF covering all audio and video attributes, format support tables, WebVTT syntax, and autoplay policy rules.
Download PDF
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React, and Node.js in one industry-ready curriculum with real projects and placement support.
120+
Chapters
40 hrs
Content
10
Projects
4.9 ⭐
Rating
HTML5 CSS3 JavaScript React.js Node.js MongoDB AI Tools

Quick Check — Chapter 16

Expand each question to check your understanding before moving on to the multiple choice quiz.

Questions & Answers
The controls attribute is a boolean that tells the browser to render its native media player UI — play/pause button, volume slider, progress/seek bar, playback speed (in some browsers), download button, and fullscreen toggle (for video). Without controls, the media element has no visible UI at all — audio is completely invisible, and video shows only the poster or the first frame. You would then need to build a custom player with JavaScript. For accessibility, always include controls unless you have a custom player that is fully keyboard-accessible.
All major browsers — Chrome, Firefox, and Safari — implement an autoplay policy that blocks media with audio. This prevents unwanted noise from tabs the user hasn't interacted with. The policy is: autoplay with audio requires that the user has previously engaged with the site (clicked, scrolled, or interacted). To make autoplay work reliably and unconditionally, you must also add the muted attribute: <video autoplay muted loop>. This is the standard pattern for hero background videos. If you need sound, trigger .play() from a button click — after user interaction, browsers allow programmatic audio playback.
The <source> element provides multiple media file options for the browser to choose from. The browser evaluates each <source> in order and plays the first one it supports — skipping the rest. This solves format compatibility: WebM has better compression but Safari has limited support; MP4 works everywhere but is larger. By listing webm first and mp4 second, Chrome/Firefox get the efficient WebM and Safari falls back to MP4. Always include the type attribute — without it the browser must download part of each file to detect the format, wasting bandwidth.
WebVTT (Web Video Text Tracks) is a plain-text file format for timed text — captions, subtitles, descriptions, and chapter markers. A .vtt file starts with the word WEBVTT, followed by numbered cue blocks each containing a timestamp range and text. The <track> element inside <video> links a WebVTT file to the video — the browser overlays the timed text on the video frame at the correct time. The kind attribute specifies the type: captions (all audio info for deaf users), subtitles (translated dialogue), descriptions (audio descriptions for blind users), chapters (navigation points).
The poster attribute specifies the URL of an image to display as the video thumbnail before playback begins. Without it, the browser shows either a black frame or the first frame of the video — which often appears blank while the video loads, causing an ugly flash. Setting a poster: creates a professional first impression, prevents content layout shift (the element has a defined size immediately), gives SEO crawlers an image to index for the video, and improves perceived performance since the thumbnail appears instantly. Always design a dedicated poster image — ideally with a play button overlaid — rather than using a random video frame.
preload="none" tells the browser to download nothing until the user explicitly presses play — best for pages with many videos or when bandwidth is precious. preload="metadata" downloads only the file's metadata (duration, dimensions, first frame for poster) — recommended in most cases as it enables showing duration without loading the full file. preload="auto" downloads the entire media file in the background — use only when the video is the primary page content and you're confident the user will watch it. Note: browsers may ignore the preload hint on mobile to save cellular data, overriding your choice.
Multiple Choice Questions
MCQ 1 of 4
Which attribute must be added alongside autoplay to guarantee a video plays automatically in all major browsers?
MCQ 2 of 4
Which <track> kind value provides all audio information — dialogue AND sound effects — for deaf users?
MCQ 3 of 4
What preload value tells the browser to download only the duration and dimensions — not the full media file?
MCQ 4 of 4
Which video format has the widest browser support and should always be provided as a fallback?
Chapter Summary
  • <audio> embeds sound; <video> embeds video — both render native browser media players when controls is present. Without controls, media is invisible and must be controlled by JavaScript.
  • Key shared attributes: controls, src, autoplay, muted, loop, preload. Video-only: poster, width, height, playsinline.
  • Use <source> inside media elements to provide multiple format fallbacks. Browser picks first supported format. Always include the type attribute. Recommended: WebM first → MP4 fallback for video; OGG first → MP3 fallback for audio.
  • <track> adds timed text — captions, subtitles, descriptions, chapters — from a WebVTT .vtt file. Add default to enable the track by default. WCAG 1.2.2 requires captions for all pre-recorded video.
  • Autoplay policy: autoplay alone is blocked with sound. autoplay muted always works. For hero background video always use autoplay muted loop playsinline aria-hidden="true".
  • Make video responsive with CSS aspect-ratio: 16/9 and width: 100%. Use preload="metadata" for performance. Always set a poster to avoid layout shift and black flash.
~9 min read
Beginner level
Chapter 16 of 40

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
If this tutorial helped you, a 5-star Google review means a lot. It helps other learners discover our free content and motivates us to keep improving.
500+ Reviews (Target)
Write a Google Review
Join WhatsApp Channel