Preload mp3 file in queue to avoid any delay in playing the next file in queue

Here’s you go. The biggest challenge I had was handling the value of this within the handler. Set your <audio> elements to preload="none". My script loads the next song as soon as you play one before it and auto-plays next song once first one finishes.

If you’re worried about Global Scope just put it in an IIFE. Enjoy!

var files = document.getElementsByTagName('audio');
var songs = [];
var index = 0;

var Song = function(element) {

this.index = index;
this.playing = function(event) {
	try {
		files[this.index].preload = "auto";
	}
	catch (e) {

	}
};
this.ended = function(event) {
	try {
		files[this.index].play();
	}
	catch (e) {

	}
};
element.addEventListener('playing', this.playing.bind(this), false);
element.addEventListener('ended', this.ended.bind(this), false); // Trick
};

for (var len = files.length, i = 0; i < len; ++i) {
index++;
songs.push(new Song(files[i]));
}
ul{
  list-style: none;
}
<!DOCTYPE html>
<html lang="en">
    <meta name="description" content="HTML5 Media Auto Player Skeleton" />
    <title>HTML5 Media Auto Player Skeleton</title>
    <style>

    </style>
</head>

<body>
        
    <main>
<ul>
	<li class="album">
		<h3 class="album-title">HTML5 Media Player w Auto Next</h3>
	</li>
	<li>
		<audio controls="controls" class="full-width" preload="metadata">
			<source src="https://rack.international/samples/AttritionDantesKitchenwWHellmixSAMPLE.mp3" type="audio/mpeg">
			<source src="https://rack.international/samples/AttritionDantesKitchenwWHellmixSAMPLE.ogg" type="audio/ogg">
			Your browser does not support the audio element.
		</audio>
	</li>
	<li>
		<audio controls="controls" class="full-width" preload="metadata">
			<source src="https://rack.international/samples/AttritionDantesKitchenRascalKlonermxSAMPLE3.mp3" type="audio/mpeg">
			<source src="https://rack.international/samples/AttritionDantesKitchenRascalKlonermxSAMPLE3.ogg" type="audio/ogg">
			Your browser does not support the audio element.
		</audio>		
	</li>
	<li>
		<audio controls="controls" class="full-width" preload="metadata">
			<source src="https://rack.international/samples/crankRingtone.mp3" type="audio/mpeg">
			<source src="https://rack.international/samples/crankRingtone.ogg" type="audio/ogg">
			Your browser does not support the audio element.
		</audio>		
	</li>
        
</body>

</html>

Leave a Comment