Adrian M. Adrian M. - 19 days ago 7
PHP Question

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>

Answer

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;
Comments