Majster
Majster

Reputation: 3701

MediaElementJs ended callback not fired

I have a problem using the MediaElementPlayer class with my web application. What I want to accomplish is to fire a method every time player plays a track to the end. My code looks like this:

$(document).ready(function()
{
    $('#audio-player').mediaelementplayer("#audio-player", 
    {
        alwaysShowControls: true,
        features: ['playpause','volume','progress'],
        audioVolume: 'horizontal',
        audioWidth: 400,
        audioHeight: 120,
        success: function(mediaElement, domObject)
        {
            mediaElement.addEventListener('ended', loadNew, false);
        }
    });

    function loadNew()
    {
        Alert("Track ended callback");
    }

    $(".play-button").click(function()
    {
        alert("Load new");
    });
});

My jQuery version is 1.7.2. I have tried other variations of this such as var player = new Media... and then player.addEventListener but all without any luck. And the funny thing is that this actually worked yesterday and today it doesn't.

Any suggestions? Thanks!

Upvotes: 1

Views: 2573

Answers (2)

Nicolas Hachet
Nicolas Hachet

Reputation: 11

In your mediaelementplayer() fonction call, be sure to not repeat "#audio-player" as first parameter :

$(document).ready(function()
{
    $('#audio-player').mediaelementplayer( 
    {
        alwaysShowControls: true,
        features: ['playpause','volume','progress'],
        audioVolume: 'horizontal',
        audioWidth: 400,
        audioHeight: 120,
        success: function(mediaElement, domObject)
        {
            mediaElement.addEventListener('ended', loadNew, false);
        }
    });

    function loadNew()
    {
        Alert("Track ended callback");
    }

    $(".play-button").click(function()
    {
        alert("Load new");
    });
});

It should fix your problem.

Upvotes: 1

Majster
Majster

Reputation: 3701

I have managed to fix it, for all future readers, code is posted below. Not much of a change but it works like charm.

$(document).ready(function()
{
    var player = new MediaElementPlayer("#audio-player",
    {
       alwaysShowControls: true,
       features: ['playpause','volume','progress'],
       audioVolume: 'horizontal',
       audioWidth: 400,
       audioHeight: 120,
       success: function(mediaElement, domObject)
       {
           mediaElement.addEventListener('ended', loadNextTrack, false);
       }
    });

    $(".play-button").click(function()
    {
        alert("Load new");
    });
});

function loadNextTrack(mediaElement, domObject)
{
   alert("Next track callback");
}

Upvotes: 3

Related Questions