Generate a Playlist for HTML5 Video

I wanted to script a playlist generator for HTML5 without using jQuery and this is what I came up with. What it does is read files from a directory and outputs it in JSON array. It’ll pass the values to JavaScript and with a bit of DOM magic, set the MP4′s path to HTML5′s player. I could’ve easily built the front end with jQuery but I wanted to see the gears of HTML5. If you don’t care about performance then use PHP’s glob() method to find files in a directory. I also added two JS functions from Apple’s dev manual. Sometimes you don’t have to reinvent the wheel.

11/22/10
I fixed the click event bug ,so now it will load the video properly. jQuery made it easier to figure out what was wrong with the links. Basically, I attached click events with the live() method to the generated links and they should play the appropriate video when clicked.

[php toolbar="true"]
<?php
//Grab the files from a directory
$dir = ‘vids’;
if(is_dir($dir)){
if($dd = opendir($dir)){
while (($f = readdir($dd)) !== false)
if($f != ‘.’ && $f != ‘..’){
$files[] = $f;
}
closedir($dd);
}
}
//Create JS’s header
header("Content-type: text/javascript");
$file = array();

foreach($files as $key => $val){
//inserts the val into the array
$file[$key] = $val;
}

//creates json obj with the array
echo ‘var obj = ‘ . json_encode($file) . ";n";
?>

// listener function changes src
function myNewSrc() {

var myVideo = document.getElementsByTagName(‘video’)[0];
myVideo.src = obj[(++i)%obj.length];
myVideo.load();
myVideo.play();

}

// function adds listener function to ended event
function myAddListener(){
var myVideo = document.getElementsByTagName(‘video’)[0];
myVideo.addEventListener(‘ended’, myNewSrc, false);

}

$(document).ready(function(){

for(i in obj){
var text = document.createTextNode(obj[i]);
var list = document.getElementById(‘list’);
var bullet = document.createElement(‘li’);
var output = document.getElementById(‘output’);

var path = "vids/" + text.nodeValue;

bullet.innerHTML= "<a href=’" + path + "’ onclick=’return false;’>" + text.nodeValue + "</a>";
list.appendChild(bullet);
output.appendChild(list);

}

$(‘#list > li a’).live(‘click’, function(e){
var t = e.target;
var $this = $(this);
var path = $this.attr(‘href’);
var myVideo = document.getElementsByTagName(‘video’)[0];

myVideo.src = path;
myVideo.load();
myVideo.play();

});

});

[/php]

You have to place the JS source tag at the bottom of the markup otherwise it won’t parse properly. It’s just good practice to load your scripts at the bottom of the document. You can also load it by creating an init() method if you want to be really nasty. I’ve set this page up so that it fits snug with the iPad’s screen width. There are ways to have fallbacks so that it degrades to Flash but that’s outside the scope of this write up. NETTUTS goes over it a bit.

[html toolbar="true"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Generate HTML5 Playlist with JSON</title>
<style type="text/css">
#player {
padding-top: 6px;
}
#output{
display:block;
width:480px;
height:220px;
background-color:#CCC;
color:#000;
padding:6px;
}

#output {width:350px; height:200px; background-color:#CCC;}
#output ul, li{list-style:none;}
hgroup{list-style:none;}

</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
</head>

<body id="index" class="home" onLoad="myAddListener()">
<header id="header" class="vid">
<div id="logo"><h1>Create a HTML5 Playlist with PHP</h1></div>
</header><!– /#header –>

<aside id="featured" class="body">
<article>
<figure>
<video src="vids/video.mp4"
controls
id="player"
poster="bluemoon_logo.jpg"
height="480"
width="720"
type="video/mp4"></video>
</figure>
<hgroup>
<h2>Video loading playlist</h2>
<div id="output"><ul id="list"></ul></div>
</hgroup>
</article>
</aside><!– /#featured –>
<script src="getPlaylist.php"></script>
</body>
</html>

[/html]

Check out the working sample to see how it’s set up. You can only view this in Safari and Chrome but maybe by 2049 HTML5 will be fully implemented. I don’t think HTML5′s video will mature anytime soon, but it doesn’t hurt to see what the future holds. It has a lot of catching up to do if it wants to out do Flash.


42 thoughts on “Generate a Playlist for HTML5 Video

  1. hey man,

    i been looking everywhere for something similar to this, I just had a question for you…

    I need to use it for AUDIO , i been looking for an audio player with a playlist that I can put on my site, do you think I can use audio tag for this code ??

    do you recommend any audio players with a playlist (html 5) ??

  2. came across this site looking for an audio playlist generator for JPlayer. i just made one for my personal use and wasn’t sure if there was much demand for one…i could clean up my code if people want it. let me know. website has email info.

    i made mine using filenames and/or ID3 info (via getID3).

  3. hey
    how about if i want to add a drop down list and every selection in that list points to a folder and so the script will get the videos from the selected folder?

    1. @CasaPonita So basically the drop down will have like a category with sublinks to the videos? It’s definitely possibly to wrap the output links with drop down mark-ups.

  4. @Thai
    i mean for e.g if i had a show with 5 seasons,and i put every season in a folder, and i put 5 selections in a drop down menu from season1 to season5.
    so when a season is selected from the drop down menu it will get only the videos in that folder and list them

    i tried sending the var from javascript to php using the $_REQUEST but it didn’t work…

    1. @CasaPonita Ah, now I see what you’re trying to do. You’re making a request with JS and then passing it PHP so that it’ll populate a list on the fly. I will think of something fancy for you. I’ve been meaning to re-visit this code but with the introduction of jQuery. It’s matter of reading your season folders first and making the request to the files within them.

    1. @casaponita Hey, not yet. I’m doing research and figuring out an elegant way to do it. Before I share it to the web community I wanna run it by you. Ill probably work on this Sunday. Wish me luck! :D

    1. @CasaPonita Yea, been busy. I’m building a jQuery plugin that will override the browser’s native video controls. I thought it would be the best way to include it in the menu as a button. Here’s a sneak peek of what it looks like. So, when you click on the playlist button, it’ll display your vids within categories. This is all work in progress. ;D

    1. @CasaPonita Thank you, basically I’m creating a html5 player that’ll utilize this playlist feature from scratch, so please be patient while I cry and moan. I’m doing a lot of it on my free time and every chance I get at lunch. I can’t to finish it!

  5. Hello,

    This is pretty close to what I was looking for. The mediafront player is really hard to get working, but this was quite simple.

    However, it could just be me, but I can only get the first three videos to play.

    Does anyone have any idea on how to fix it?

    1. @Chris Thanks man. It means a lot. There is a bug in which only the first three vids play. I can’t seem to figure why. Probably mind blowing dumb. :

  6. The function myNewSrc() does not go to the next clip after the video ends, it just loads the hard-coded /vids/video3.mp4 Should it not load the next clip in the playlist??

    1. @Aron Yea, there’s a bug within that function and it’s suppose to load the next video. When I revisit this code, I will update it. I hope it was informative for you though.

  7. @Aron Thanks! By the way, I fixed that bug where videos weren’t loading properly. I’ve updated the working sample and the code to reflect the update. After introducing jQuery to it, I was able to determine the bug and corrected the issue.

    1. @mironik Hi, I’d be more than happy to help you. I’m new to PHP too and I know what it’s like. So, what’s the problem? Make sure all of the files are in the same folder.

      1. I took a look at your site with the script and I found the bug. Look for this in the code:
        [php toolbar="true"]
        echo ‘var obj = ‘.json_encode($file).’;n’;
        [/php]
        And replace it with this:

        [php toolbar="true"]
        echo ‘var obj = ‘ . json_encode($file) . ";n";
        [/php]
        It has to be double quotes to render the next carriage. Let me know if that helped.

    1. @mironik We’re all beginners at some point. I know I sure am. You’re doing a great job by trying out different things. If I were to add thumbnails to the links this is what I would do. Look for this:
      [php toolbar="true"]
      bullet.innerHTML= "<a href=’" + path + "’ onclick=’return false;’>" + text.nodeValue + "</a>";
      [/php]

      Add a variable that is tied up with the image. Let’s put the thumbnail in the same folder with the video and call it “thumb_video1.jpg”. thumb_ is just the prefix and video1 is the name of the video. Now let’s add this:
      [php toolbar="true"]
      var empty_string = ”;
      var name = text.nodeValue.replace(‘.mp4′, empty_string);
      var thumb = "<img src=’" + path + "thumb_" + name + ".jpg" + "’ class=’thumb’>" ;
      bullet.innerHTML= thumb + "<a href=’" + path + "’ onclick=’return false;’>" + text.nodeValue + "</a>";
      [/php]

      Basically, we’re just removing the “.mp4″ extension from the string and placing a thumbnail that’s labeled “thumb_video1.jpg” next to the link. The logic is that we’re naming the thumb to match with our video so that it will tie up nicely. Let me know if you have any questions.

  8. in my opinion it should be like this, just as I have too many unnecessary image links

    Am I blzu, whether I learn slowly

    var path = “vids/” ;
    var empty_string = ”;
    var name = text.nodeValue.replace(‘.mp4′, empty_string)
    var thumb = “” ;
    bullet.innerHTML= thumb +”” +text.nodeValue + ““;

  9. in my opinion it should be like this, just as I have too many unnecessary image links
    Am I close, I am learning that slowly

    previous post was incorrect, this is what I wanted to say

    var path = “vids/” ;
    var empty_string = ”;
    var name = text.nodeValue.replace(‘.mp4′, empty_string)
    var thumb = “” ;
    bullet.innerHTML= thumb +”” +text.nodeValue + ““;

    1. I gotta fix that so people can leave code on the page. You can do that but don’t forget to remove the text value from:
      [php]
      var path = ‘vids/’ ;
      [/php]

  10. There is still a problem, see:
    http://streamingnet.org/
    I think the problem is easily solved if the JSON Playlist created only with the filter *. mp4, because now create and *. jpg.

    then we could introduce another variable such as “description ” to “desc_video1.txt, as was done with” thumb_video1.jpg

    I think it would be interesting.
    …. but how feasible? !

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>