Sub topic 2
Pointing an element at a media file
This chapter assumes you know basic HTML attributes, how relative and absolute URLs work, and how to attach event listeners in JavaScript. Earlier chapters introduced the audio and video elements. This one covers the simplest way to load a file into them, the src attribute, and what the browser does after you set it.
The src attribute
The src attribute holds the URL of one media file. Setting it makes the browser start the resource selection process. The browser fetches the file and decodes enough of it to show the duration, and for video the dimensions. It does this only as far as the preload setting allows.
<audio controls src="podcast-episode.mp3">
<a href="podcast-episode.mp3">Download the episode</a>
</audio>The URL follows the same rules as href on a link or src on an image:
- A relative URL such as
podcast-episode.mp3or../media/intro.mp4resolves against the document's base URL. This is the page address unless abaseelement changes it. - An absolute URL such as
https://cdn.example.com/intro.mp4is used as written. - A root-relative URL such as
/media/intro.mp4resolves against the site origin.
Setting src gives the browser exactly one candidate. If the browser cannot play that file, it does not try anything else. To offer alternatives you need source elements, which a later chapter covers. The two mechanisms interact in one way you must know:
What happens after you set src
The browser does not report one "loaded" state. It moves through a sequence of events, and the element exposes its progress through two read-only properties, networkState and readyState.
The events mean the following:
loadstart: the browser began fetching.loadedmetadata: duration and, for video, dimensions are known. Readingdurationbefore this event givesNaN.loadeddata: the first frame or sample at the current position is available.canplay: playback can begin, though it may stall if the data arrives slowly.canplaythrough: the browser estimates it can play to the end without stalling.
The readyState property is a number from 0 to 4 that tracks the same progress:
| Value | Name | Meaning |
|---|---|---|
| 0 | HAVE_NOTHING | No information about the media yet |
| 1 | HAVE_METADATA | Duration and dimensions known |
| 2 | HAVE_CURRENT_DATA | Data for the current position only |
| 3 | HAVE_FUTURE_DATA | Enough data to play a little further |
| 4 | HAVE_ENOUGH_DATA | Enough to play through, by the browser's estimate |
The networkState property reports fetching activity. 0 is empty, 1 is idle, 2 is loading, and 3 is no source found. Value 3 is the one to check when an element appears to do nothing at all.
Reading the resolved URL
The src property returns the absolute URL, while getAttribute('src') returns the text you wrote. The currentSrc property reports the URL the browser actually chose. It is the only reliable property when source children are involved, and it is empty until selection finishes.
const audio = document.querySelector('audio');
console.log(audio.getAttribute('src')); // "podcast-episode.mp3"
console.log(audio.src); // "https://example.com/podcast-episode.mp3"
audio.addEventListener('loadedmetadata', () => {
console.log(audio.currentSrc, audio.duration);
});Changing the file from JavaScript
You can assign a new value to src at any time. The browser abandons the current resource and restarts the loading sequence. This is how a playlist works with one element.
const player = document.querySelector('audio');
const tracks = ['one.mp3', 'two.mp3', 'three.mp3'];
let index = 0;
player.addEventListener('ended', async () => {
index = (index + 1) % tracks.length;
player.src = tracks[index];
try {
await player.play();
} catch (err) {
console.error('Could not start next track:', err.name);
}
});
player.src = tracks[0];Setting src also resets currentTime to 0 and fires emptied if media was already loaded. It does not preserve the playbackRate or the paused state in a way you should rely on, so set what you need after loading.
To release a file entirely, remove the attribute and call load():
player.removeAttribute('src');
player.load();Assigning src = '' is a poor substitute. The empty string resolves to the page URL, which the browser then tries to fetch as media and reports as an error.
Starting at a position with a media fragment
A URL fragment can ask for part of the file. The #t= syntax takes start and optional end times in seconds.
<video controls src="lecture.mp4#t=30,90"></video>Current browsers honor this by starting at 30 seconds and stopping at 90. Treat it as a convenience. It does not make the browser download only that range, and it does not replace server-side clipping.
Handling errors
When a fetch or decode fails, the element fires an error event and sets its error property to a MediaError object. Its code property tells you why.
| Code | Constant | Typical cause |
|---|---|---|
| 1 | MEDIA_ERR_ABORTED | The user or script stopped loading |
| 2 | MEDIA_ERR_NETWORK | Connection dropped during download |
| 3 | MEDIA_ERR_DECODE | File is corrupt or uses features the decoder rejects |
| 4 | MEDIA_ERR_SRC_NOT_SUPPORTED | Bad URL, 404 response, wrong MIME type, or unsupported format |
Code 4 covers several different problems, which makes it hard to debug. When you see it, check these in order:
- Open the URL directly in a browser tab. A 404 or an HTML error page means the path is wrong.
- Check the
Content-Typeresponse header. A server that sendstext/htmlorapplication/octet-streamfor an MP3 can cause failures in some browsers. A later chapter covers correct MIME types. - Confirm the codecs inside the container are ones the browser supports. A
.mp4file is only a container, and the video or audio stream inside it may use a codec the browser cannot decode.
const media = document.querySelector('video');
media.addEventListener('error', () => {
const { code, message } = media.error;
console.error(`Media error ${code}: ${message}`);
});Fallback content inside the element does not appear when the file fails to load. It appears only in browsers that do not recognize the element at all. A broken src in a modern browser produces a blank player, so listen for error if you want to show a message.
Controlling how much is fetched
The preload attribute hints at how much the browser should download before the user presses play. It takes three values:
none: fetch nothing until playback is requested.metadata: fetch enough to learn the duration and dimensions.auto: the browser may download the whole file.
It is a hint, not a command. Browsers on mobile networks or with data-saver on often ignore it. The later chapter on playback attributes covers the choice in detail.
Exercise
A page has <video controls src="a.mp4"><source src="b.webm" type="video/webm"></video>. Which file does the browser load, and which property would you read to confirm it?
Show answer
The browser loads a.mp4, because the src attribute is present and the source child is ignored. Read currentSrc after the loadedmetadata event to confirm the chosen URL.
Exercise
You set video.src = 'next.mp4' and then read video.duration on the next line. You get NaN. Why, and what should you do?
Show answer
Duration is unknown until the browser has loaded metadata, which happens asynchronously. Read it inside a loadedmetadata event listener instead.