Search code examples
phpfileaudiorandomplayback

Using PHP to play sound


my php code to fetch all sound files, random way, in a folder is this:

$files = glob("audio/*.mp3");
$random = $files[array_rand($files)];

and to play them i use:

<audio src="<?php echo $random; ?>" width="400" height="200" controls></audio>

What i want is to play the sound files pressing a HTML button tag and not seeing the default HTML5 audio player. Just like Spotify or similar.

I tried making it with button onclick="function()" but with javascript wich is a client language i don't know a way to loop all files in my folder, just like i did with the php code above.

Any ideas? Many thanks...


Solution

  • Few minutes after asking i solved the question by myself. Been dealing with this four a couple of hours, so here it is:

    <a onclick="this.firstChild.play()"><audio src="<?php echo $random; ?>"></audio>&#9658;</a>
    

    Used the browser DOM and a html special caracter & #9658;. It does the trick, in spite of not allowing the use of an icon image.

    Thanks to all :)