Add a stop function to the html5 audio element

0 Flares Filament.io 0 Flares ×

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).







Last Updated On : 30th June 2013

Subscribe to get updates delivered to your inbox

About Silver Moon

Php developer, blogger and Linux enthusiast. He can be reached at m00n.silv3r@gmail.com. Or find him on

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 StumbleUpon 0 Filament.io 0 Flares ×