Lesson 10 +10 XP

Audio and Video

Web pages can play sound and movies right in the page: no separate app needed!

Video: <video>

<video> needs src (or <source> children) and controls so people can press play.

Code

html
<video src="movie.mp4" controls></video>

The text inside shows up if the browser can't play it:

Code

html
<video src="movie.mp4" controls>
  Your browser doesn't support video.
</video>

Audio: &lt;audio&gt;

Same idea for sound!

Code

html
<audio src="song.mp3" controls></audio>

Multiple sources: &lt;source&gt;

Different browsers like different formats. Give them choices!

Code

html
<video controls>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.webm" type="video/webm">
  Your browser doesn't support video.
</video>

The browser tries each &lt;source&gt; in order and plays the first one it can.

Fancy features

  • autoplay: starts playing by itself (usually blocked by browsers until you interact).
  • loop: plays over and over.
  • muted: starts silent.
  • poster=&quot;pic.jpg&quot;: a cover picture shown before the video plays.
  • width/height: video size.
Code

html
<video src="clip.mp4" controls loop muted poster="cover.jpg" width="400"></video>

Subtitles: &lt;track&gt;

&lt;track&gt; adds subtitles or captions. It points to a .vtt file with the captions.

Code

html
<video controls>
  <source src="movie.mp4" type="video/mp4">
  <track src="captions.vtt" kind="captions" srclang="en" label="English">
</video>

Kinds: captions, subtitles, descriptions, chapters, metadata.

TL;DR

  • &lt;video&gt; and &lt;audio&gt; play media in the page.
  • controls adds the play/pause buttons.
  • &lt;source&gt; offers multiple formats.
  • autoplay, loop, muted, poster are handy extras.
  • &lt;track&gt; adds subtitles.