Using <source> in <audio> and <video> tags

Hello hello all! I have a question that may be simple, but I was just curious:

I’m working through the front end development track, currently learning about semantic html, and specifically about the <audio> element. I noticed in the example provided, there was a <source> element nested within the <audio>, and within that <source> there was a src attribute linking to the file, see below:

<audio>
  <source src="iAmAnAudioFile.mp3" type="audio/mp3">
</audio>

but in the following example of adding a video to a page, it is shown to us as:

<video src="coding.mp4" controls>Video not supported</video>

My question is, what is the difference between using the element, and just using the src attribute? Are they interchangeable, or is one more semantically correct than the other?

Hey @nicdelgadillo_m welcome to the forums.

Quoting this from the CC docs entry on the tag:

The <source> element allows for multiple sources or file formats to be associated with the <audio>, <video>, and <picture> tags. In case one source is incompatible with a given browser, another one can be referenced. If all else fails, the browser will attempt to display fallback content.

Basically, in case 1 format is not supported you can use another.

Thanks for the quick response, that makes a lot of sense! So would it best practice to use the source element rather than the attribute to try to reach as many browers as possible?

Yes. The more file types the better. But if you add too many the page would probably lag.

1 Like