Before HTML5, it was very hard to embed audio in your website. In most cases, you had to use flash.
Now thanks to the <audio> element, creating an audio player for your website is much easier.
In this tutorial I will show you how to embed sounds in a web page. We will also take a look at how to toogle play/pause with one button by using simple jQuery.DEMO
How HTML5 Audio Works
The audio element is simple to use.
Just insert the full url to the sound file between the quotes.
To make the sound start automatically use the autoplay attribute.
<audio autoplay> <source src="sound1.mp3"> </audio>
You can also make the sound repeat again and again by using the loop attribute. It can be useful in creating an online game for example, where you want the music to play endlessly.
Adding controls to our audio player
Sometimes it is nice to add controls, so that user can play,pause or mute the music.
Keep in mind that the controls will look and behave different in each browser.
This is the code for a looping html5 audio player with controls:
<audio controls loop>
You can also use two more attributes:
- muted – Specifies that the audio output should be muted
- preload – Specifies if and how the audio should be loaded when the page loads. For example if you set preload=”none”, the browser will not load the audio file on page load.
Play/pause music with one button using jQuery
All we need is a speaker icon
and some code.
<a id="mtoogle" style="cursor:pointer;"> <img src="https://ftutorials.com/wp-content/uploads/2013/08/speaker.png"></a> <audio id="playTune" autoplay> <source src="sound1.mp3"> </audio>
And the jQuery
Tip: Insert the jQuery library in the head section of your website:
And don’t forget. Most of the users don’t like when opening some website to hear some unrelated sound or music. In most cases that is stressful for them. So you must be very careful when embeding music in your website. Especially if you use the autoplay attribute.