Adrian M.
Adrian M.

Reputation: 7443

PHP/HTML5 Random Sound Player on Page Load

I am trying to make a php/html5 sound player that will: 1. scan the files in a folder called "sound" and select only mp3 files 2. at each page load, play a random sound from the ones in the "sound" folder.

So far it works pretty well, except sometimes the path of the source is not a .mp3 but also "/sound/" and some times "/.."

Do you have any suggestions? I there a way to scan for mp3's only and not dirs or other extensions?

Thank you very much for any reply..

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php 
$dir = 'sound/';
$scan = scandir($dir);
$size = sizeof($scan);
$random = rand(1, $size);
$randomFile = $scan[$random];
$fileLocation = $dir. $randomFile;
$explode = explode(".", $randomFile);
$extension = $explode[1];
?>
<title>Test</title>

</head>
<body>
    <?php echo $fileLocation; ?>

    <audio autoplay>
        <source src="<?php echo $fileLocation; ?>" type="audio/<?php echo $extension; ?>"></source>
    </audio>
</body>
</html>

Upvotes: 0

Views: 1355

Answers (2)

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

PHP scans .. and . when you scan a directory. You will have to skip .. and . files that are scanned when you scan a directory in linux. Try this code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php 
$dir = 'sound/';
$scan = scandir($dir);
$size = sizeof($scan);
regen:
$random = rand(1, $size);
$randomFile = $scan[$random];
if( $randomFile == 'sound/..' || $randomFile == 'sound/.' ) 
    goto regen;
$fileLocation = $dir. $randomFile;
$explode = explode(".", $randomFile);
$extension = end($explode);
?>
<title>Test</title>

</head>
<body>
    <?php echo $fileLocation; ?>

    <audio autoplay>
        <source src="<?php echo $fileLocation; ?>" type="audio/<?php echo $extension; ?>"></source>
    </audio>
</body>
</html>

or allow only mp3 extensions like below:

$dir = 'sound/';
$scan = scandir($dir);
$size = sizeof($scan);
regen:
$random = rand(1, $size);
$randomFile = $scan[$random];
$fileLocation = $dir. $randomFile;
$explode = explode(".", $randomFile);
$extension = end($explode);

if( $extension != 'mp3' ) goto regen;

Upvotes: 1

Squiggs.
Squiggs.

Reputation: 4474

scandir scans files and directories as per the documentation.

$dir = 'sound/';
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
      $x =  pathinfo($filename);
      if( $x['extension'] == 'mp3' )
         $files[] = $filename;

}

you can then pick from your files array.

Upvotes: 1

Related Questions