ildrean
ildrean

Reputation: 11

Playing audio files with jPlayer from a database

I have a large project that generates a list of music files for a user and I want to use an instance of jPlayer to play a file when the it is in gets clicked on.

Currently, this is the code at the head of the page:

$(document).ready(function(){

    $("#jquery_jplayer_1").jPlayer({
        ready: function () {
            $(this).jPlayer("setMedia", {
                mp3: "http://www.jplayer.org/audio/mp3/Miaow-07-Bubble.mp3" //test file
            });
        },
        ended: function (event) {   
            $(this).jPlayer("play");
        },
        swfPath: "/js",
        supplied: "mp3"
    });

This is just the code for loading the initial file, and it works completely.

Also at the head, I have this block that changes the current file when a row gets clicked. It gets the md5 hash that's set as the id on the row and passes it to a php file which returns the file path. I've checked this with firebug and it seems to be returning a valid path.

    $("tr").click(function() {      
        var md5 = $(this).attr("id");
        var filename = "";
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                filename = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","md5tofilename.php?md5="+md5,true);
        xmlhttp.send();

        $("#jquery_jplayer_1").jPlayer("setMedia", {
            mp3: filename           
        });
        $("#jquery_jplayer_1").jPlayer("play");
        return false;
    });
});

For whatever reason, clicking a row does not cause the new file to play, although it does unset the current file. jPlayer sets the time to '0:00' and acts like there is no file loaded.

For reference, here is an example of a generated row:

<tr id="bbac3c5090c5ca76ce7a02b8112dec0a" class="row1">
    ...
</tr>

And the response from calling the php file for a test value:

GET http://localhost/md5tofilename.php?md5=1234567890 200 OK 36ms   

"http://www.jplayer.org/audio/mp3/Miaow-07-Bubble.mp3"

Any insight into what I'm doing wrong or what's causing the problem would be greatly appreciated.

Upvotes: 1

Views: 1956

Answers (1)

Keith Maurino
Keith Maurino

Reputation: 3432

After setting the media and then trying to play on the following line the plugin will not be ready yet to play. Try something like this to attempt to auto-play.

$("#jquery_jplayer_1").jPlayer("setMedia", {
    mp3: filename           
}).jPlayer("play"); // Attempts to Auto-Play the media

Upvotes: 2

Related Questions