HTML5
How to Specify the URL of the Media File in HTML5?
There are two ways to tell an HTML5 <audio> or <video> element where its media file lives: the src attribute directly on the media tag for a single file, or one or more nested <source> elements when you want to offer multiple formats as fallbacks.
Method 1: The src Attribute
For a single media file, put the URL directly in the src attribute of the <audio> or <video> tag. This is the simplest approach when you only provide one format.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Media src Attribute</title>
</head>
<body>
<h2>Using src directly</h2>
<video width="400" controls
src="https://www.w3schools.com/html/mov_bbb.mp4">
Your browser does not support video.
</video>
</body>
</html>Method 2: The <source> Element
To provide several formats, omit src on the media tag and add multiple <source> children, each with its own src and type. The browser plays the first format it supports and skips the rest — this maximises compatibility.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Media source Elements</title>
</head>
<body>
<h2>Using multiple source elements</h2>
<audio controls>
<source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
<source src="horse.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
</body>
</html>| Method | Best for | Format fallback? |
|---|---|---|
| src attribute | A single media file | No |
| <source> elements | Multiple formats | Yes |
Always include the type attribute on each <source> (for example type="audio/mpeg"). It lets the browser skip formats it cannot play without downloading them first.
Key Takeaways
- Use src on the media tag for a single file.
- Use nested <source> tags to offer multiple format fallbacks.
- The browser picks the first supported <source>.
- Set the type attribute on each <source> for efficiency.
