Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to successfully destroy a MediaElementPlayer and create a new one

Here's the scenario:

I have a page that contains a video element which is set up with a video. The source of this video may be HTML5 video with multiple sources (and Flash fallback) or a YouTube video. Beneath this is a number of images which serve as video thumbnails, clicking on one should load the appropriate video, by destroying the existing MediaElementPlayer and creating a new one on the same video element.

This creates the initial player on page load:

$('video').mediaelementplayer({ alwaysShowControls: true });

And this is intended to change the player when one of the images is clicked:

$('video').mediaelementplayer({
   alwaysShowControls: true,
   success: function(media, dom, player) {
      console.log('success!');
   },
   error: function() {
      console.log('error!');
   }
});

But it doesn't work. The success function is never entered (neither is error) and nothing appears to happen.

I guess the library still thinks that the original player exists or something, and have tried a number of things to try and tell it that this isn't the case, for example:

mejs.meIndex = 0
mejs.players = []

To no effect, and setting:

window.mejs = null;
window.MediaElementPlayer = null;
window.MediaElement = null;

Just breaks things :)

Can anyone out there help? I'm sure I'm missing something simple here so I'd be very grateful if someone could point out what! Thanks in advance.

like image 315
Ian Devlin Avatar asked Oct 07 '22 09:10

Ian Devlin


1 Answers

You can use the remove() method of medialementjs, set the type and src attribute of your video element and then reinitialize mediaelementjs if the video type has changed.

Could look something like this:

function setSource(url, type) {
    var vid = $('#video').first();
    if (vid.attr('type') != type) {
        vid.get(0).player.remove();
        vid.attr('type', type).attr('src', url);
        vid.mediaelementplayer({
            success: function(media, dom, player) {
                player.play();
            }
        })

    }
}

If you don't only have mp4 and youtube you can add additional logic to only reinitialize when needed. Works perfect for me.

like image 171
Nic Avatar answered Oct 10 '22 23:10

Nic