Jesse Sliter
Jesse Sliter

Reputation: 243

Changing html5 video source with preloading

I'm setting up a video portfolio site to showcase different concepts for software devs, and there are often multiple versions of the same video.

I wrote the following javascript to change videos and it works fine locally, the problem is that once its hosted changing videos breaks the video player. I'm guessing the cause is because the new video is not loaded. Any ideas?

function switcher(wrapper, e, source, container, video){

//get current version and turn off its style
var off = document.getElementById(wrapper).getElementsByClassName("versionActive")[0];
off.className = "version";

//turn on the new button
e.className = "versionActive";

var videoSource = document.getElementById(source);
var videoContainer = document.getElementById(container);

lastPlayingVideo.currentTime = 0;
lastPlayingVideo.pause();
lastPlayingVideo = videoContainer;

videoSource.setAttribute('src', video);
videoContainer.load();
videoContainer.play();

}

The html for the video player looks like this:

<video id="container1" controls="" loop="" preload="auto" width="1280" height="720">
     <source id="video1" src="videos/Reminder.mp4" type="video/mp4">
</video>

Upvotes: 0

Views: 1435

Answers (1)

Lauromine
Lauromine

Reputation: 1493

Try :

videoContainer.addEventListener('canplay', function() {
   videoContainer.play();
   videoContainer.removeEventListener('canplay');
});
videoSource.setAttribute('src', video);
videoContainer.load();

canplay is fired when the browser supposes you have received enough of the file and you can continue playing it considering your connection speed.

Upvotes: 1

Related Questions