Lesson 10 +10 XP

Audio and Video

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.

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

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

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

Audio: <audio>

Same idea for sound!

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

Multiple sources: <source>

Different browsers like different formats. Give them choices!

<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 <source> 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="pic.jpg": a cover picture shown before the video plays.
  • width/height: video size.
<video src="clip.mp4" controls loop muted poster="cover.jpg" width="400"></video>

Subtitles: <track>

<track> adds subtitles or captions. It points to a .vtt file with the captions.

<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

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