Search code examples
ajaxjplayer

Make jPlayer play again without page reload


Our users us IE7 and I need to play a sound if there are alert messages for dispatchers.

This works fine when the page is loaded but if the dispatcher leaves a page open and messages have been received previously and responded to.... then when new messages are received, the sound does not seem to work.

What am I doing wrong in using jPlayer? I just want to play the sound continuously as long as messages are there.

My Ajax call

$.ajax({
    type: "POST",
    url: "/Messages/ViewMessages.aspx/GetMessages",
    data: "{messageId:" + 45 + "}",
    contentType: "application/json; charset=utf-8",
    cache: false,
    dataType: "json",
    timeout: 60000,
    success: function(data) {
        if (data.d.length > 0) {
            showPanic(data.d);
            var sound = "/JavaScript/jQuery/UI/js/Audio/Air Plane Ding-SoundBible.com496729130.mp3";
     playSound(sound);
        }
        else {
            $("#dialog").dialog("destroy");
        }

    }

function playSound(sound) {
            $("#jquery_jplayer_1").jPlayer({
                ready: function() {
                    $(this).jPlayer("setMedia", {
                        mp3: sound
                    }).jPlayer("play");
                },
                loop: true,
                swfPath: "/JavaScript/jQuery/UI/js/jQuery.jPlayer.2.1.0/Jplayer.swf",
                supplied: "mp3"
            });
            $("#jquery_jplayer_1").jPlayer("play");}

Solution

  • try this change in playSound. Click here to run the code in jsFiddle.

    function playSound(sound) {
        var $player = $("#jquery_jplayer_1");
        if ($player.data().jPlayer && $player.data().jPlayer.internal.ready === true) {
            $player.jPlayer("setMedia", {
                mp3: sound
            }).jPlayer("play");
        }
        else {
            $player.jPlayer({
                ready: function() {
                    $(this).jPlayer("setMedia", {
                        mp3: sound
                    }).jPlayer("play");
                },
                loop: true,
                swfPath: "/JavaScript/jQuery/UI/js/jQuery.jPlayer.2.1.0/Jplayer.swf",
                supplied: "mp3"
            });
        }
    }