PHP & MySQL, Demos, Tutorials

Load MP3's from a folder with option to play on page

Thus tutorial will show you how to grab videos from a folder and list them on a page, once listed an MP3 file can be clicked on and then played in a player or downloaded.

Player from http://www.alsacreations.fr/dewplayer-en

Source Code

<?php ob_start();?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MP3 Test</title>
</head>
<body>

<?php

   $dirname = "music/";
   $files = scandir($dirname);
   $ignore = array(".", "..", ".DS_Store");

   echo '<ul>';
   foreach($files as $curfile){
       if(!in_array($curfile, $ignore)) {
           echo "<li><a href='?file=".$curfile."'>$curfile</a></li>n ";
       }
   } 
   echo '</ul>'; 


   if(isset($_GET['file'])){

    $file = $_GET['file'];

    echo '<object type="application/x-shockwave-flash" data="dewplayer.swf" width="200" height="20" id="dewplayer" name="dewplayer">
    <param name="movie" value="dewplayer.swf" />
    <param name="flashvars" value="mp3='.$dirname.$file.'" />
    <param name="wmode" value="transparent" />
    </object>';

    echo '<br /><a href="?download='.$file.'">Download</a>';

   }  

  if(isset($_GET['download'])){

       $file = $dirname.$_GET['download'];
       header ("Content-type: octet/stream");
       header ("Content-disposition: attachment; filename=".$file.";");
       header("Content-Length: ".filesize($file));
       readfile($file);
       exit; 
  }

?>
</body>
</html> 
<?php ob_flush(); ?>

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.