George
George

Reputation: 581

preload html5 audio while it is playing

For HTML5 Audio, let's say you have a list of two songs you want to play. Currently I have it set up so that when the current song stops playing, it loads the new song and plays it. I want to have it so that it loads the next song while the current song is finishing, maybe 20 seconds before the current song finishes. I tried to change the src attribute for the audio object while the song is playing, but that just immediately stops playback for the current song. Is there some other method that allows me to preload the next song while the current song is playing?

Upvotes: 3

Views: 3224

Answers (2)

Daniel
Daniel

Reputation: 890

You could use jQuery to create a jQuery object:

var nextSong = document.createElement('audio'); //Creates <audio></audio>
nextSong = $(nextSong); //Converts it to a jQuery object
$(nextSong).attr('autoplay') = false; //You don't want this dynamically loaded audio to start playing automatically
$(nextSong).attr('preload') = "auto"; //Make sure it starts loading the file
$(nextSong).attr('src') = url_to_src; //Loads the src

This should start load the song into an element in the browser's memory and when the song is over, call something like:

$(audio).replace(nextSong);

This isn't tested. You probably don't even need jQuery.

This may work without jQuery:

var nextSong = document.createElement('audio');
nextSong.autoplay = 'false';
nextSong.preload = 'auto';
nextSong.src = url_to_src;

Give it a whirl and let me know!

Upvotes: 3

Matt Diamond
Matt Diamond

Reputation: 11696

This might be off the mark, but have you tried calling the element's load() method?

http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#loading-the-media-resource

Edit:

Ah, I think I misunderstood the problem. You want to play two songs back to back in the same media element? I'm not sure how feasible that is... it might be easier to place each song in its own Audio element. You could always dynamically generate these, if you're worried about flexibility.

Upvotes: 1

Related Questions