Random Auto-Play Audio with Caption + Cookie

This demo will load a random song every time the page is refreshed. The song title is displayed in the caption box and a toggle switch stops and starts playback. A cookie remembers when sound is manually turned off so that it won't auto-play again on return visits. Stop auto-play altogether by following instructions in the JS.

Works in modern browsers and IE9+

Note: Auto-play is disabled in iOS to preserve mobile data packages.

Please view the source of this page for HTML markup, CSS and JS. The relevant PHP is provided below.

You are listening to: ' Twilight In Paris '

PHP Code

This snippet gets all the mp3s in a folder;

<?php
$files = glob('relative/path/to/audio/*.mp3');
// get all .mp3 files from folder
$fname = $files[array_rand($files)]; // get a random filename
$ftext = ucwords(str_replace('_', ' ', basename($fname, '.mp3'))); // format text for display
?>

Here's how a random mp3 populates the audio player;

<audio id="music" preload="auto">
    <source src="<?php echo $fname; ?>"/>
</audio>

And this is how the nicely formatted filename gets in to the infobox;

<div id="infobox">You are listening to: '<b><?php echo $ftext; ?></b>'</div>

Related

More demos and snippets

Did you find this useful? There are more demos and code snippets this way.