HTML5 audio fade in and out

Wednesday, 22 April 2015

⚠️ This is an old post

It's possibly been exported and imported from at least three different blogging platforms over the years. That probably means, at best, there are broken images and links. If the post is technical in nature, any advice is probably out of date and irrelevant. Or it is really old, it was the wafflings of a teenager with too much time on his hands working out what blogging is… If it is the latter I would probably cringe if I re-read it. But it's here because it's part of my past, not my present.

You've been warned! Onwards…

I’ve just discovered that the animate function within jQuery can provide more than just visual animation. One such ‘animation’ is adjusting the volume in the audio tag, thus creating a good method for creating fade in or fade out:


$(‘.btn-fadeout’).on(‘click’, function(e) {
	e.preventDefault();
	audio_player = $(‘audio.audio_player`);
	audio_player.animate(
		{ volume: 0 }, // Target volume
		500, // How long should the fadeout take
		function() {
			audio_player[0].pause(); // Pause the audio
			audio_player[0].currentTime = 0; // Be kind, rewind.
			audio_player[0].volume = 1; // Reset volume
		}
	);
}
Back to all posts