I have researched this question a lot, yet have not found a suitable solution.
What I have is a few images using album covers and when you click on them, I want a random song from the album to be pulled. The albums are 01-05, and their cover images are in them. When clicked, they call song = "<?php echo (random_song("album_number")); ?>";
which is then embedded in a div with id #player
.
PHP:
<?php
function random_song($dir) {
$files = array (
(array) glob('01/*.mp3'),
(array) glob('02/*.mp3'),
(array) glob('03/*.mp3'),
(array) glob('04/*.mp3'),
(array) glob('05/*.mp3')
);
$set = substr($dir,0,2) - 1;
shuffle($files[$set]);
$key = array_rand($files[$set]);
$file = $files[$set][$key];
return $file;
}
?>
So far, I have gotten it to play a song; however, it never picks another song. If I click on one album, it will pick a song; click on a second one, it will play a song. Click back on the first one, and it plays the same song.
I have tried adding shuffle()
, as you can see, but it has not made a difference.
I have also done a var_dump()
on every part of $files
to ensure that glob()
is working; there have been no problems.
I'm stuck. What do I need to do?
Solution:
What Fritz van Campen said was correct: the php is only called once. It was written in the <script>
and called as soon as it was parsed, therefore each album only called upon the song it was originally coded for. What I needed to do, as he suggested, was to move the song picker to JavaScript. My Solution:
var songs = <?php echo json_encode($files); ?>;
...
var set = parseInt(dir.substr(0,2))-1;
var song = songs[set][Math.floor(Math.random() * songs[set].length)];
...which transfers the array created by the php to JavaScript, and uses the same system to pick a random song.
Thank you for answering!