Introduction to Audio in HTML5
The HTML5 brought us many new features and facilities, one of which is to allow us to insert audio players directly on our website through the audio tag, without needing any external plugin for it, and best of all, in a super simple and intuitive.
Many developers, especially those who develop online radio sites, or the site of any customer that wants its users to listen some kind of music on your website, much work had to provide this functionality to their customers.
With the arrival of html5 for developers got a little easier, you can now put videos and audios directly into their designs using a simple tag native HTML5.
There are several ways to put an audio on our page, as shown in the following table:
|autoplay||autoplay||Sets the audio will start playing as soon as it is ready.|
|controls||controls||The controls are shown.|
|loop||loop||Sets the audio will start playing again when finished.|
|preload||preload||Sets the audio will be loaded while the page is read. This attribute is ignored if the autoplay attribute is set.|
|src||url||URL of the file to be played.|
Let's see some examples of these, let's first create an example using autoplay.
Listing 1: HTML code of the page with autoplay
<!DOCTYPE HTML> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <title>HTML5 Audio Autoplay</title> </head> <body> <audio autoplay="autoplay"> <source src="your_audio_file.mp3" type="audio/mp3" /> </audio> </body> </html>
Remembering that, we need to put the link to your audio file. Mp3 inside the src attribute to the audio power to run, otherwise nothing will run.
If you want the audio is not touched once the page is loaded and is displayed controls play / pause and volume of execution, simply use the controls attribute.
Listing 2: Code HTML attribute controls
<!DOCTYPE HTML> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <title>HTML5 Audio</title> </head> <body> <audio controls="controls"> <source src="your_audio_file.mp3" type="audio/mp3" /> </audio> </body> </html>
The result of the above code can be seen in the image below. As we can see, is inserted into our page an audio player standard HTML5.
Figure 1: Tag with audio controls
Like the video tag, audio tag has some compatibility problems with different browsers. Below you will see a table showing the compatibility of various audio formats and different browsers.
|Format||IE 8||Firefox 3.5||Opera 10.5||Chrome 3.0||Safari 3.0|
As we can see, with this new HTML5 tag was much easier to insert a sound in a web page, which formerly had to be done by flash, now we can insert directly into the page.
Unfortunately some browsers still do not have this compatibility, which makes it increasingly difficult to develop, but the trend of the Web is that all major browsers have full support for HTML5 and CSS3.
I hope you enjoyed, until next article.