In this section, we will learn what HTML <source> element is and how to use it.
What is <source> Tag in HTML?
For HTML, media elements like <audio>, <video> and <picture> you need an external resource (an audio or video or picture file).
But the problem with browsers is that they can’t work with all media types for audio and videos and pictures! This means, if we have one audio file, for example, we need multiple formats of it so that browsers can pick the one they can work with.
So the HTML <source> element is used to bring multiple formats (for audio or video files) into an audio or video player. (Also for pictures)
Basically, we put an HTML <source> element in the body of an HTML media element like <video> or <audio> and specify the address of the external audio or video file.
If there’re multiple formats for one file, we add multiple <source> elements in the body of that <video> or <audio> element.
Note: Each <source> element can bring only one format of the file.
There are two important attributes belonging to <source> element:
HTML <source> element src Attribute:
The src attribute is used to set the address (URL) of the external media file (like audio or video file).
HTML <source> element type Attribute:
The type attribute is used to set the type of that media file set in the `src` attribute.
For example, if the file is a video of type “.mp4” then the value of this attribute would be “video/mp3”.
Or if the file is an audio file of type “.ogg” then the value of this attribute would be “audio/ogg”
The value we set for the `type` attribute is mainly known as Internet Media Type (AKA MIME Type).
HTML <source> Tag Syntax:
<source src = “file-address” type = “MIME Type”>
Example: using <source> tag in HTML
See the Pen using <source> tag in HTML by Omid Dehghan (@odehghan) on CodePen.