How to play audio in the HTML5 and how to control the audio play using in HTML element ?

Sheonarayan
Posted by in HTML 5 category on for Beginner level | Points: 250 | Views : 23778 red flag
Rating: 5 out of 5  
 2 vote(s)

In this article, we are going to learn How to play audio in the HTML5 and how to control the audio play using in HTML element.

In this article, we are going to learn new form elements introduced in HTML5.

Please remember that HTML5 is still being improved and all browsers doesn't support all features of HTML5. The screen shots you see above are taken mostly from Opera and few of them from Google Chrome.

Get 500+ ASP.NET web development Tips & Tricks and HTML5 Online training here.

How to play audio in the HTML5?

To play audio in HTML5, we can use the audio tag which is introduced in HTML5. At the time of writing this ebook, any one of .mp3, .wav or .ogg audio files are supported in all new browsers that supports HTML5.

Code

<audio src="Shiv_Ganga01.mp3" autoplay controls id="audio1">

audio is not supported.

</audio>

Output

The attributes like autoplay, controls are described in below video points.

How to control the audio play using our own HTML element?

To control the audio play in the web page using our own HTML element we can take help of JavaScript. In the below code snippet we have prepared a UI with three button elements, two range elements and a lable.

Code – HTML

<audio src="Shiv_Ganga01.mp3" id="audio1">

Audio is not supported.

</audio>

<div>

<input type="button" id="btnPlay" value="Play" onclick="PlayNow()" />

<input type="button" id="btnPause" value="Pause" onclick="PauseNow()" />

<input type="button" id="btnMute" value="Mute" onclick="MuteNow()" />

<br />

Volume :<input type="range" min="0" max="1" step="0.1" id="volume"

onchange="ChangeVolume()">

<br />

Time lapsed:<input type="range" step="any" id="seekbar"

onchange="ChangeTheTime()"><label id="lblTime">-:--:--</label>

 

</div>


In the above code snippet, we have attached onclick event of the Play, Pause and Mute buttons to methods PlayNow(), PauseNow() and MuteNow() respectively. Two range elements are kept with onchange event that are attached with ChangeVolume() and ChangeTheTime() method. The label element is for displaying the elapsed time of the audio.

Code – Javascript

<script src="../Scripts/ModernizrBuild.js" type="text/javascript"></script>

 

<script type="text/javascript">

// check if audio is supported in the browser or not

if (Modernizr.audio) {

alert("Audio is supported");

}

else {

alert("Audio is NOT supported");

}

 

 

// get the audio, volume and seekbar elements

var audio = document.getElementById("audio1");

var volumeRange = document.getElementById('volume');

var seekbar = document.getElementById('seekbar');

 

// attach timeupdate, durationchange event to the audio element to update the

time in the lable and seekbar

window.onload = function () {

// go to http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-

EventTarget-addEventListener to know more about addEventListener

// (false is for bubbling and true is for event capturing)

audio.addEventListener('timeupdate', UpdateTheTime, false);

audio.addEventListener('durationchange', SetSeekBar, false);

volumeRange.value = audio.volume;

}

 

// executeswhen volume element is changed

function ChangeVolume() {

var myVol = volumeRange.value;

audio.volume = myVol;

if (myVol == 0) {

audio.muted = true;

} else {

audio.muted = false;

}

}

 

// fires when page loads, it sets the min and max range of the video

function SetSeekBar() {

seekbar.min = 0;

seekbar.max = audio.duration;

}

// fires when seekbar is changed

function ChangeTheTime() {

audio.currentTime = seekbar.value;

 

}

 

// executes when audio plays and the time is updated in the audio element, this

writes the current duration elapsed in the label element

function UpdateTheTime() {

var sec = audio.currentTime;

var h = Math.floor(sec / 3600);

sec = sec % 3600;

var min = Math.floor(sec / 60);

sec = Math.floor(sec % 60);

if (sec.toString().length < 2) sec = "0" + sec;

if (min.toString().length < 2) min = "0" + min;

document.getElementById('lblTime').innerHTML = h + ":" + min + ":" + sec;

 

seekbar.min = audio.startTime;

seekbar.max = audio.duration;

seekbar.value = audio.currentTime;

}

 

// executes when Play button is clicked

function PlayNow() {

if (audio.paused) {

audio.play();

} else if (audio.ended) {

audio.currentTime = 0;

audio.play();

}

}

 

// executes when Pause button is clicked

function PauseNow() {

if (audio.play) {

audio.pause();

}

}

// executes when Mute button is clicked

function MuteNow() {

if (audio.muted) {

audio.muted = false;

volumeRange.value = audio.volume;

}

else {

audio.muted = true;

volumeRange.value = 0;

}

}

 

</script>

In the above code snippet, you will notice that we have used a .js file called ModernizrBuild.js that has been downloaded from http://www.modernizr.com/download/ website.

A little of Modernizr:

As per the website(http://www.modernizr.com/) Modernizr is an open-source JavaScript library that helps you build the next generation of HTML5 and CSS3-powered websites.It basically helps you to check if a particular feature of HTML5 is supported in the browser or not. To know more about the Modernizr, please visit its website as mentioned above.

In this case I am using this to check if audio is supported into the browser from which my page is browsed. If not, on the page loads user gets “Audio is NOT supported” as an alert.

As soon as the page loads, it checks for the Modernizr.audio property, if this is true it means that audio is supported in the browser that is being used to browse this page.

Next we have found out the audio, volume and seekbar elements and stored them in the variable.


On load of the window we have set the timeupdate and durationchange event of the audio element that helps use to update the time elapsed for audio play in the label element and setting the min and max range for the seekbar range element. We are also setting the volume element value to the defult audio element volume that will be the system default volume.


ChangeVolume()


On change of the volume range element, we have set audio volume to the value selected by the the user. If the value selected by the user is 0, we have simply muting the audio otherwise unmuting it.

SetSeekBar()

In this function, we are setting the minimum and maximum range of the seekbar range element.

ChangeTheTime()


In this function, we are setting the current time of the audio element to the seekbar selected value by the user.


UpdateTheTime()


In this function, we are simply getting the current position of the audio play and getting the hour, minute and seconds lapsed and writing in the label element. We are also setting the seekbar min, max and value to the audio startTime, duration and currentTime values respectively so that the seekbar value is in sync with the audio running position.


PlayNow()


This function simply checks if audio is paused, it plays (by calling the play() method on audio element) the audio else if it is ended already then change its position to 0 (ie beginning) and plays it.


PauseNow()


This function checks if the audio is already playing, if yes then call pause() function that pauses the audio.


MuteNow()
 

In this function, we check if the audio is muted already, then set muted property of the audio element to false so that it will be unmuted and set the volume range element to the audio volume. If the audio is not muted then it mutes and set the volume range element to 0.

How to play Video HTML5?

Playing video and controlling it is similar to playing the audio in HTML5, just replace the audio tag to video and it should work fine !!!!

Hope you liked this article, keep reading my forth coming article on HTML5.

Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Omniitstudent on: 3/1/2012 | Points: 25


1) In asp.NET ,during which page life cycle does view state get load..

Posted by: Patel28rajendra on: 3/14/2012 | Points: 25
Hi

Sheo Narayan

Its very very Interesting
You always write interesting Articles !!!

Keep it up!

Thanks
Rajendra Patel
Posted by: The_Ryan on: 8/31/2012 | Points: 25
HTML5 is a new way to get the things done easily, audio and video addition is quite like image addition.

Visit for social network development: http://www.talentsfromindia.com/social-network-web-developers-programmers.html

Login to post response

Comment using Facebook(Author doesn't get notification)