Add a stop function to the html5 audio element

By | June 30, 2013

The Audio element of html5 does not yet have a stop function, but has a pause function. So here is a simple trick to add a stop function to your Audio elements by modifying the prototoype of the class.

//Give the Audio element a stop function
HTMLAudioElement.prototype.stop = function()
{
	this.pause();
	this.currentTime = 0.0;
}

The function would first pause the audio element, then would set the seek position to 0.0 which is the beginning.
Can be used comfortably like this

var aud = new Audio();
aud.src = 'background.ogg';
aud.play();

//stop it
aud.stop();

The technique can be used to add more useful functions to the element as per the need.

Note :

You could try adding to Audio class directly like this

Audio.prototype.stop = function()
{
	this.pause();
	this.currentTime = 0.0;
}

Using the above, aud.stop() would work in chrome and opera but not in Firefox (v. 17.0.1 at the time of writing this article).

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

Leave a Reply

Your email address will not be published. Required fields are marked *