Semantic HTML, why use a separate <source> tag instead of including a src in the <audio> tag?

https://www.codecademy.com/paths/fscj-22-web-development-foundations/tracks/fscj-22-fundamentals-of-html/modules/wdcp-22-semantic-html-44fa9550-9f1e-49de-b4d6-295acba84038/lessons/semantic-html/exercises/audio-and-attributes

I was working through the above linked section covering semantic html and noticed something I found curious.

<audio controls>
        <source src="https://content.codecademy.com/courses/SemanticHTML/dogBarking.mp3" type="audio/mp3">
      </audio>

is the way the course wants you to complete the challenge, but I found that the following works just as well.

<audio controls src="https://content.codecademy.com/courses/SemanticHTML/dogBarking.mp3" type="audio/mp3">
</audio>

Is there any particular reason to use one over the other? Readability looks the same from my point of view. Is it just personal preference?

Hi Nick,

The <source> tag(s) nested inside the <audio> tag is to embed more than one different audio source file–such as MP3, WAV, or OGG. With more than one file, the browser can choose from (depending on the circumstances) the options and run the first one it supports. While it’s perfectly fine to use src= for singular files, it’s good to keep <source> in mind for multiple files.

(<source> is also supported by <video> and <picture>)

I hope that helps!

4 Likes

This was really helpful thank you! I have a follow up question, I hope its okay to post here since its additional details on the same initial topic.

Would you then list all of the various source files within one source element or would you need to create a new one for each file?

So

<audio>
  <source src="audiofile.mp3" type="audio/mp3">
  <source src="audiofile.wav" type="audio/wav">
</audio>

or

<audio>
  <source src="audiofile.mp3" type="audio/mp3"  src="audiofile.wav" type="audio/wav">
</audio>

Hello again,

Sorry for the late response, but you would list them all with a separate <source> tag you you displayed with the first example!

1 Like

Wonderful, thank you!