It is essential to have control on the played audio. You may not like the default shape of the player or want to have more controlling buttons and options. Sometimes it is needed to call some functions at specific event and etc. In these series of posts we deal with HTML5 audio element events and attributes to handle it better. Now learn load and play options. Now learn load and play options . . .
The element can get automatically played when the page loaded, by adding ‘autoplay‘ attribute to the main definition tag. It is also possible to reload the sound when it is finished by ‘loop‘ attribute, there:
<audio controls autoplay loop>
<source src=”1.ogg” type=”audio/ogg”>
<p>The browser doesn’t support the audio element.</p>
</audio>
Try it and see the effect.
If you use large files, it is better not to load the entire file immediately; maybe it hurts the users. But the advertisements usually play automatically. However, this feature is controlled by ‘preload‘ attribute:
<audio src=”1.mp3″ preload=”auto” controls></audio>
Three values are allowed; ‘auto‘ express that the whole file must be loaded completely, when the page is loading. In reverse, ‘none‘ prevents any loading until the user push the ‘play‘ button. It is also possible to load only the file information (like its duration) by ‘metadata‘.
In the case of controlling the events we need a scripting language like JavaScript. Let us make an invisible audio element and control it by our own buttons:
<audio id=”aud” src=”2.ogg”></audio>
<div>
<button onclick=”document.getElementById(‘aud’).play()“>Play</button>
<button onclick=”document.getElementById(‘aud’).pause()”>Pause</button>
<button onclick=”document.getElementById(‘aud’).volume+=0.1″>Volume +</button>
<button onclick=”document.getElementById(‘aud’).volume-=0.1″>Volume -</button>
</div>
The result is:
By the above codes, you can play, pause and change the volume of the audio element. This was some basic operations by inline JavaScript code; but for more advanced controlling, it is needed to open a scripting tag.
There exist many attributes and events for the audio element, but as we want to deal with them in practice, we start our example series from the next post. So continue with us . . .