HTML from Scratch: Adding Audio and Video to Your Website — For Beginners. Lesson #26


Creating an interactive website is hard to imagine without media content. Whether it’s background music for atmosphere, a podcast, or a promotional video—HTML5 provides simple and powerful tools to implement these elements. In this article, we will cover the HTML basics for working with multimedia.

1. Embedding Audio: The <audio> Tag

To add sound in HTML5, the <audio> tag is used. It allows you to control playback, volume, and the visual appearance of the player.

Basic Example

<audio controls>
  <source src="music.mp3" type="audio/mpeg">
  Your browser does not support audio.
</audio>

Breaking down the key points:

  • controls: This attribute adds standard browser buttons (Play, pause, volume).

  • <source>: Inside the tag, you can specify multiple file sources in different formats to ensure support across all browsers.

  • Text inside the tag: This will only appear if the user’s browser is outdated and does not support HTML5.

How to add background music?

If you want the music to play automatically when the page loads, add the autoplay attribute. However, keep in mind: modern browsers block automatic sound playback unless the user has interacted with the page (e.g., by clicking on it).

<audio src="background-music.mp3" autoplay loop>
</audio>
  • loop: forces the music to play in a continuous loop.

2. Embedding Video: The <video> Tag





Working with video in HTML for beginners is very similar to working with audio. The main difference is that video requires you to specify dimensions (width and height).

Code Example

<video width="640" height="360" controls poster="preview.jpg">
  <source src="video.mp4" type="video/mp4">
  Your browser does not support video.
</video>

Useful Attributes:

  • poster: A link to an image that will be shown before the video starts (thumbnail).

  • muted: Useful for video backgrounds so the clip can start automatically without annoying sound.

3. Optimization Tips

While learning HTML media, it’s important to keep website performance in mind:

  1. Format Choice: Use .mp3 for audio and .mp4 for video—these are standards supported by all modern devices.

  2. File Size: Optimize media before uploading. Don’t insert a 50 MB audio file if it can be compressed to 3–5 MB without losing quality.

Working with <audio> and <video> tags is a great way to bring your project to life. Now you know how to add media content, set up controls, and make your site more expressive. Start small: try creating a simple page with your favorite playlist or a presentation video!