Home Snippets Projects Donate

Get Snippets For:

   Java    HTML/CSS JavaScript

Audio

Code Description:

Audio can be easily incorporated into a web page with the <audio> tag. Within the <audio> tag, the <source> tag is placed which is used to specify where the audio file is located and what format. Multiple <source> tags can be placed within the <audio> tags. If the first source is not supported by the browser, it will move on and try the next. You can place text within the <audio> tag which will display if none of the source elements work.

The "controls" attribute determines if the Pause, Play, and Sound controls are visible. The "autoplay" attribute determines if an audio clip will being to play once loaded. Autoplay is a desktop-only feature. The "loop" attribute will let the audio replay over and over again.

There are three audio formats that are permitted:

If you would like to download our incredibly annoying sample audio file, it is provided here:

Download - myAudio.mp3

Audio with Controls Syntax:

<audio controls>
   <!-- Only one source is required. Multiple sources allow for a better chances of audio working on all browsers -->
   <source src="myAudio.mp3" type="audio/mpeg">
   <source src="myAudio.wav" type="audio/wav">
   <source src="myAudio.ogg" type="audio/ogg">
   Audio tag not supported in this browser
</audio>

Audio without Controls Syntax:

<audio>
   <!-- Only one source is required. Multiple sources allow for a better chances of audio working on all browsers -->
   <source src="myAudio.mp3" type="audio/mpeg">
   <source src="myAudio.wav" type="audio/wav">
   <source src="myAudio.ogg" type="audio/ogg">
   Audio tag not supported in this browser
</audio>

Autoplay Loop Audio Syntax:

<audio autoplay loop>
   <!-- Only one source is required. Multiple sources allow for a better chances of audio working on all browsers -->
   <source src="myAudio.mp3" type="audio/mpeg">
   <source src="myAudio.wav" type="audio/wav">
   <source src="myAudio.ogg" type="audio/ogg">
   Audio tag not supported in this browser
</audio>

Runnable Audio Example Code:

<!DOCTYPE html>
<html>
    <head>
        <title>Audio Example</title>
    </head>
 
    <body>
       
       <audio controls>
          <!-- Only one source is required. Multiple sources allow for a better chances of audio working on all browsers -->
          <source src="myAudio.mp3" type="audio/mpeg">
          <source src="myAudio.wav" type="audio/wav">
          <source src="myAudio.ogg" type="audio/ogg">
          Audio tag not supported in this browser
       </audio>

    </body>
</html>

How to Run This Code:

Simply paste this code into a plain text file with the ".html" extension and save it. You will then be able to open it in the web browser of your choice. Make sure to download our sample audio file and have it in the same folder as the HTML file.

Related Links: