HTML audio

HTML audio element is used to add the audio in a page. It is very easy to add an audio. Beacuse it uses src attribute to specify the address of audio just like an image.

audio element

audio element adds audio stream using src attribute.

Example

The Audio would play automatically

Try </>

src attribute specifies the address of the audio.

audio related attributes

autoplay attribute

The audio plays automatically without any controls when we add autoplay attribute.

Example

<p>The Audio is being added.</p>
<audio src="sample.mp3" autoplay>
</audio>

Try </>

controls attribute

controls attribute adds controls such as volume, play, and pause.

See the above given examples.

loop attribute

loop attribute plays the audio again upon reaching at the end.

Example

<p>The audio element contains the loop attribute.</p>
<audio src="sample.mp3" loop> 
</audio>

Try </>

muted attribute:

muted attribute initially sets the volume of audio to zero. It is a boolean attribute.

Example

<p>The Audio is muted initially</p>
<audio src="sample.mp3" muted> 
</audio>

Try </>

File Path problems (audio)

You may face file path problems while adding an audio on a page. Now, what is the problem?

  • To understand it we take an example of an audio that we want to add on a page.

  • If the audio and the page are at the same location, then there is no problem. In this case, you just need to write the name of the file with extension (.ogg, .mp3 ) in the src attribute.

  • But if both audio and page are at different locations, then you have to write the proper address of the file.

  • See the following example to understand.

Example


 <p>The Audio is muted initially</p>
  <audio src="http://www.codingb.com/html/sample.mp3" muted> 
 </audio>
	
Try </>

Always remember to add a forward slash between address and name of the audio.

Summary

loop attribute enables the audio to seek back to the start of video.

controls adds controls in the audio.

autoplay attribute plays the audio automatically after the page is loaded.

source tag can also be used to audio stream in the page.



Was this article helpful?