This post is the first in a series that will discuss the HTML audio element, web audio in general, and all of the various ways that sound can be heard on a web page.
The simplest way to add audio to your web page is not very different that adding an image. You can use an
<audio src="path/to/your/audio.mp3" type="audio/mpeg"></audio>
This is the minimal code you would need to build a custom interface, but if you want an audio player (with play button and volume) to show up on your web page, you also have to add the boolean attribute,
<audio src="path/to/your/audio.mp3" type="audio/mpeg" controls></audio>
The way this default player looks depends completely on the web browser. For example, on Chrome it might look like this:
But on Firefox it might look like this:
So as easy as it is, you don’t have a lot of control over the appearance this way. In future posts I will explain the several ways to customize your own player.
Web Audio Fallback
Perhaps you have different versions of the audio, let’s say one is an MP3 and another is an OGG file, which is an open source audio file type that not all browsers know how to use. But the OGG file is a smaller file, and you want it to be used wherever it can be, therefore making the loading time faster and the user experience better. You could use the source element like this:
<audio controls> <source src="path/to/your/audio.ogg" type="audio/ogg"> <source src="path/to/your/audio.mp3" type="audio/mpeg"> </audio>
The browser will try to understand the first one, and if it does not support that first file type, it will then try the second one. You can add as many fallbacks as you like, even adding iframes or default text if the user’s browser just simply doesn’t understand any of them
<audio controls> <source src="path/to/your/audio.oga" type="audio/ogg"> <source src="path/to/your/audio.ogg" type="audio/ogg"> <source src="path/to/your/audio.mp3" type="audio/mpeg"> <iframe width="100%" height="166" scrolling="no" frameborder="no" allow="autoplay" src=".."></iframe> Your browser does not play HTML audio. </audio>
There are also other attributes other than
controls that you can add to the
audio element. The common attributes are:
Of course you can always attach:
And some of the less common audio attributes that are sometimes used for more advanced code are:
So you could have something like:
<audio id="my-song" class="song" src="path/to/your/audio.mp3" type="audio/mpeg" controls autoplay loop></audio>
More details on these attributes can be found at https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio
Next Up: Audio Element CSS
As mentioned above, there’s not a lot you can do to style the default player in each respective browser, but there are a few things you can do to add add a little more customization and character to your player. In the next post we will discuss some of these ways to style your web audio player with CSS.